In [1]:
import utils; reload(utils)
from utils import *
In [2]:
import keras
In [3]:
x = random((30, 2))
y = np.dot(x, [2., 3.]) + 1
https://keras.io/getting-started/sequential-model-guide/
keras.layers.Dense : https://keras.io/layers/core/#dense
Just your regular densely-connected NN layer
In [5]:
keras_lm_model = keras.models.Sequential([
keras.layers.Dense(1, input_shape = (2,))
])
Before training a model, you need to configure the learning process, which is done via the compile method. It receives three arguments
In [6]:
keras_lm_model.compile(optimizer = keras.optimizers.SGD(lr = 0.1),
loss = 'mse')
keras_lm_model.evaluate: Computes the loss on some input data, batch by batch
In [8]:
keras_lm_model.evaluate(x, y, verbose = 0)
Out[8]:
In [9]:
keras_lm_model.fit(x, y, nb_epoch = 20, batch_size = 1, verbose = 2)
Out[9]:
In [10]:
keras_lm_model.evaluate(x, y, verbose = 0)
Out[10]:
In [11]:
keras_lm_model.get_weights()
Out[11]:
In [12]:
from vgg16 import Vgg16
In [13]:
vgg = Vgg16()
In [14]:
model = vgg.model
In [15]:
model.summary()
In [16]:
# removing the last layer
model.pop()
In [17]:
model.summary()
In [18]:
# making all the layers as non-trainable
for layer in model.layers:
layer.trainable = False
In [19]:
# add a new dense layer
model.add(
keras.layers.Dense(2, activation = 'softmax')
)
In [20]:
model.summary()
In [21]:
# create batch objects
gen = image.ImageDataGenerator()
In [26]:
??get_batches
In [22]:
train_batches = gen.flow_from_directory(
directory = './data/redux/train/',
target_size = (224, 224),
shuffle = True,
batch_size = 12,
class_mode='categorical'
)
In [23]:
valid_batches = gen.flow_from_directory(
directory = './data/redux/valid/',
target_size = (224, 224),
shuffle = True,
batch_size = 12,
class_mode='categorical'
)
In [ ]:
??model.fit
In [ ]:
??model.fit_generator
In [24]:
model.compile(
optimizer = keras.optimizers.RMSprop(lr = 0.1),
loss = 'categorical_crossentropy',
metrics = ['accuracy']
)
In [25]:
train_batches.n
Out[25]:
In [26]:
model.fit_generator(
generator = train_batches,
samples_per_epoch = train_batches.n,
nb_epoch = 1,
validation_data = valid_batches,
nb_val_samples = valid_batches.n,
verbose = 2
)
Out[26]:
In [ ]:
??vgg.test
In [27]:
non_shuffled_valid_batches = gen.flow_from_directory(
directory = './data/redux/valid/',
target_size = (224, 224),
shuffle = False,
batch_size = 12,
class_mode='categorical'
)
In [28]:
# get predicted probabilities
predicted_probs = model.predict_generator(non_shuffled_valid_batches, non_shuffled_valid_batches.n)
In [29]:
predicted_probs[:8]
Out[29]:
In [30]:
# plotting few images
plots([
keras.preprocessing.image.load_img(non_shuffled_valid_batches.directory + non_shuffled_valid_batches.filenames[0]),
keras.preprocessing.image.load_img(non_shuffled_valid_batches.directory + non_shuffled_valid_batches.filenames[1])
],
titles = predicted_probs[:2, 1])
In [31]:
predicted_probs
Out[31]:
In [ ]: