forked from CyberZHG/keras-drop-block
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
305 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,4 @@ pip install keras-drop-block | |
|
||
## Usage | ||
|
||
```python | ||
|
||
``` | ||
See [fashion mnist demo](./demo/mnist.py). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
import keras | ||
import keras.backend as K | ||
import numpy as np | ||
from keras.datasets import fashion_mnist | ||
from keras_drop_block import DropBlock2D | ||
|
||
|
||
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() | ||
|
||
x_train = np.expand_dims(x_train.astype(K.floatx()) / 255, axis=-1) | ||
x_test = np.expand_dims(x_test.astype(K.floatx()) / 255, axis=-1) | ||
|
||
y_train, y_test = np.expand_dims(y_train, axis=-1), np.expand_dims(y_test, axis=-1) | ||
|
||
train_num = round(x_train.shape[0] * 0.9) | ||
x_train, x_valid = x_train[:train_num, ...], x_train[train_num:, ...] | ||
y_train, y_valid = y_train[:train_num, ...], y_train[train_num:, ...] | ||
|
||
|
||
def get_dropout_model(): | ||
model = keras.models.Sequential() | ||
model.add(keras.layers.Dropout(input_shape=(28, 28, 1), rate=0.3, name='Input-Dropout')) | ||
model.add(keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu', padding='same', name='Conv-1')) | ||
model.add(keras.layers.MaxPool2D(pool_size=2, name='Pool-1')) | ||
model.add(keras.layers.Dropout(rate=0.2, name='Dropout-1')) | ||
model.add(keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', padding='same', name='Conv-2')) | ||
model.add(keras.layers.MaxPool2D(pool_size=2, name='Pool-2')) | ||
model.add(keras.layers.Dropout(rate=0.2, name='Dropout-2')) | ||
model.add(keras.layers.Flatten(name='Flatten')) | ||
model.add(keras.layers.Dense(units=256, activation='relu', name='Dense')) | ||
model.add(keras.layers.Dropout(rate=0.2, name='Dense-Dropout')) | ||
model.add(keras.layers.Dense(units=10, activation='softmax', name='Softmax')) | ||
model.compile( | ||
optimizer='adam', | ||
loss='sparse_categorical_crossentropy', | ||
metrics=['accuracy'], | ||
) | ||
return model | ||
|
||
|
||
dropout_model = get_dropout_model() | ||
dropout_model.summary() | ||
dropout_model.fit( | ||
x=x_train, | ||
y=y_train, | ||
epochs=10, | ||
validation_data=(x_valid, y_valid), | ||
callbacks=[keras.callbacks.EarlyStopping(monitor='val_acc', patience=2)] | ||
) | ||
dropout_score = dropout_model.evaluate(x_test, y_test) | ||
print('Score of dropout:\t%.4f' % dropout_score[1]) | ||
|
||
|
||
def get_drop_block_model(): | ||
model = keras.models.Sequential() | ||
model.add(DropBlock2D(input_shape=(28, 28, 1), block_size=7, keep_prob=0.8, name='Input-Dropout')) | ||
model.add(keras.layers.Conv2D(filters=64, kernel_size=3, activation='relu', padding='same', name='Conv-1')) | ||
model.add(keras.layers.MaxPool2D(pool_size=2, name='Pool-1')) | ||
model.add(DropBlock2D(block_size=5, keep_prob=0.8, name='Dropout-1')) | ||
model.add(keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', padding='same', name='Conv-2')) | ||
model.add(keras.layers.MaxPool2D(pool_size=2, name='Pool-2')) | ||
model.add(DropBlock2D(block_size=3, keep_prob=0.8, name='Dropout-2')) | ||
model.add(keras.layers.Flatten(name='Flatten')) | ||
model.add(keras.layers.Dense(units=256, activation='relu', name='Dense')) | ||
model.add(keras.layers.Dropout(rate=0.2, name='Dense-Dropout')) | ||
model.add(keras.layers.Dense(units=10, activation='softmax', name='Softmax')) | ||
model.compile( | ||
optimizer='adam', | ||
loss='sparse_categorical_crossentropy', | ||
metrics=['accuracy'], | ||
) | ||
return model | ||
|
||
|
||
drop_block_model = get_drop_block_model() | ||
drop_block_model.summary() | ||
drop_block_model.fit( | ||
x=x_train, | ||
y=y_train, | ||
epochs=10, | ||
validation_data=(x_valid, y_valid), | ||
callbacks=[keras.callbacks.EarlyStopping(monitor='val_acc', patience=2)] | ||
) | ||
drop_block_score = drop_block_model.evaluate(x_test, y_test) | ||
print('Score of dropout:\t%.4f' % dropout_score[1]) | ||
print('Score of DropBlock:\t%.4f' % drop_block_score[1]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
from .drop_block import DropBlock2D | ||
from .drop_block import DropBlock1D, DropBlock2D |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
import os | ||
import random | ||
import tempfile | ||
import unittest | ||
import keras | ||
import numpy as np | ||
from keras_drop_block import DropBlock1D | ||
|
||
|
||
class TestDropBlock1D(unittest.TestCase): | ||
|
||
def test_training(self): | ||
input_layer = keras.layers.Input(shape=(100, 3)) | ||
drop_block_layer = DropBlock1D(block_size=3, keep_prob=0.7)(input_layer) | ||
model = keras.models.Model(inputs=input_layer, outputs=drop_block_layer) | ||
model.compile(optimizer='adam', loss='mse', metrics={}) | ||
model_path = os.path.join(tempfile.gettempdir(), 'keras_drop_block_%f.h5' % random.random()) | ||
model.save(model_path) | ||
model = keras.models.load_model( | ||
model_path, | ||
custom_objects={'DropBlock1D': DropBlock1D}, | ||
) | ||
model.summary() | ||
inputs = np.ones((1, 100, 3)) | ||
outputs = model.predict(inputs) | ||
self.assertTrue(np.allclose(inputs, outputs)) | ||
|
||
input_layer = keras.layers.Input(shape=(3, 100)) | ||
drop_block_layer = DropBlock1D(block_size=3, keep_prob=0.7, data_format='channels_first')(input_layer) | ||
model = keras.models.Model(inputs=input_layer, outputs=drop_block_layer) | ||
model.compile(optimizer='adam', loss='mse', metrics={}) | ||
model_path = os.path.join(tempfile.gettempdir(), 'keras_drop_block_%f.h5' % random.random()) | ||
model.save(model_path) | ||
model = keras.models.load_model( | ||
model_path, | ||
custom_objects={'DropBlock1D': DropBlock1D}, | ||
) | ||
model.summary() | ||
inputs = np.ones((1, 3, 100)) | ||
outputs = model.predict(inputs) | ||
self.assertTrue(np.allclose(inputs, outputs)) | ||
|
||
def test_mask_shape(self): | ||
input_layer = keras.layers.Input(shape=(100, 3)) | ||
drop_block_layer = keras.layers.Lambda( | ||
lambda x: DropBlock1D(block_size=3, keep_prob=0.7)(x, training=True), | ||
)(input_layer) | ||
model = keras.models.Model(inputs=input_layer, outputs=drop_block_layer) | ||
model.compile(optimizer='adam', loss='mse', metrics={}) | ||
model_path = os.path.join(tempfile.gettempdir(), 'keras_drop_block_%f.h5' % random.random()) | ||
model.save(model_path) | ||
model = keras.models.load_model( | ||
model_path, | ||
custom_objects={'DropBlock1D': DropBlock1D}, | ||
) | ||
model.summary() | ||
inputs = np.ones((1, 100, 3)) | ||
outputs = model.predict(inputs) | ||
for i in range(3): | ||
print((outputs[0, :, i] > 0.0).astype(dtype='int32')) | ||
inputs = np.ones((1000, 100, 3)) | ||
outputs = model.predict(inputs) | ||
keep_prob = 1.0 * np.sum(outputs > 0.0) / np.prod(np.shape(outputs)) | ||
self.assertTrue(0.6 < keep_prob < 0.8, keep_prob) | ||
|
||
input_layer = keras.layers.Input(shape=(3, 100)) | ||
drop_block_layer = keras.layers.Lambda( | ||
lambda x: DropBlock1D(block_size=3, keep_prob=0.7, data_format='channels_first')(x, training=True), | ||
)(input_layer) | ||
model = keras.models.Model(inputs=input_layer, outputs=drop_block_layer) | ||
model.compile(optimizer='adam', loss='mse', metrics={}) | ||
model_path = os.path.join(tempfile.gettempdir(), 'keras_drop_block_%f.h5' % random.random()) | ||
model.save(model_path) | ||
model = keras.models.load_model( | ||
model_path, | ||
custom_objects={'DropBlock1D': DropBlock1D}, | ||
) | ||
model.summary() | ||
inputs = np.ones((1, 3, 100)) | ||
outputs = model.predict(inputs) | ||
for i in range(3): | ||
print((outputs[0, i, :] > 0.0).astype(dtype='int32')) | ||
inputs = np.ones((1000, 3, 100)) | ||
outputs = model.predict(inputs) | ||
keep_prob = 1.0 * np.sum(outputs > 0.0) / np.prod(np.shape(outputs)) | ||
self.assertTrue(0.6 < keep_prob < 0.8, keep_prob) | ||
|
||
def test_sync_channels(self): | ||
input_layer = keras.layers.Input(shape=(100, 3)) | ||
drop_block_layer = keras.layers.Lambda( | ||
lambda x: DropBlock1D(block_size=3, keep_prob=0.7, sync_channels=True)(x, training=True), | ||
)(input_layer) | ||
model = keras.models.Model(inputs=input_layer, outputs=drop_block_layer) | ||
model.compile(optimizer='adam', loss='mse', metrics={}) | ||
model_path = os.path.join(tempfile.gettempdir(), 'keras_drop_block_%f.h5' % random.random()) | ||
model.save(model_path) | ||
model = keras.models.load_model( | ||
model_path, | ||
custom_objects={'DropBlock1D': DropBlock1D}, | ||
) | ||
model.summary() | ||
inputs = np.ones((1, 100, 3)) | ||
outputs = model.predict(inputs) | ||
for i in range(1, 3): | ||
self.assertTrue(np.allclose(outputs[0, :, 0], outputs[0, :, i])) | ||
inputs = np.ones((1000, 100, 3)) | ||
outputs = model.predict(inputs) | ||
keep_prob = 1.0 * np.sum(outputs > 0.0) / np.prod(np.shape(outputs)) | ||
self.assertTrue(0.6 < keep_prob < 0.8, keep_prob) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters