如何引用keras?
如果keras对您的研究有帮助,请在出版物中引用。BibTeX例子如下:
@misc{chollet2015keras,
title={Keras},
author={Chollet, Fran\c{c}ois and others},
year={2015},
publisher={GitHub},
howpublished={\url{https://github.com/fchollet/keras}},
}
如何在GPU上运行keras?
如果运行在TensorFlow后端上,代码会自动运行在检测到的GPU上。
如果运行在Theano后端上,可使用方法有:
1、使用Theano标志
THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py
'gpu'根据你的设备更改识别(例如gpu0, gpu1等等)
2、设置 .theanorc
3、在代码最前面手动设置theano.config.device,theano.config.floatX
-
import theano -
theano.config.device = 'gpu' -
theano.config.floatX = 'float32'
如何保存Keras模型?
不推荐用pickle或者cPickle来保存Keras模型。
可以使用model.save(filepath)将Keras模型保存到HDF5文件,包含:
-模型结构,可重建模型
-模型权重
-训练设置(损失、优化器)
-优化器状态,可恢复训练
然后使用keras.models.load_model(filepath)重新实例化模型。load_model会使用保存的训练设置重新编译模型。
例如:
-
from keras.models import load_model -
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' -
del model # deletes the existing model -
# returns a compiled model -
# identical to the previous one -
model = load_model('my_model.h5')
如果你只需要保存模型的结构,不需要权重和训练设置,则可以:
-
# save as JSON -
json_string = model.to_json() -
# save as YAML -
yaml_string = model.to_yaml()
生成的JSON/YAML文件具有可读性,如需要可以手工修改。
也可以从这个数据中重新构建新模型:
-
# model reconstruction from JSON: -
from keras.models import model_from_json -
model = model_from_json(json_string) -
# model reconstruction from YAML -
from keras.models import model_from_yaml -
model = model_from_yaml(yaml_string)
如果只需要保存模型的权重,可以在HDF5文件中使用以下代码。注意你需要已安装HDF5和h5py。
model.save_weights('my_model_weights.h5')
假定已实例化模型,然后可以将保存的权重加载到具有相同结构的模型中去
model.load_weights('my_model_weights.h5')
如果需要将权重加载到不同结构(有一些相同层),例如为细调或者转化学习,可以用层名称载入权重
model.load_weights('my_model_weights.h5', by_name=True)
举例如下:
-
""" -
Assume original model looks like this: -
model = Sequential() -
model.add(Dense(2, input_dim=3, name="dense_1")) -
model.add(Dense(3, name="dense_2")) -
... -
model.save_weights(fname) -
""" -
# new model -
model = Sequential() -
model.add(Dense(2, input_dim=3, name="dense_1")) # will be loaded -
model.add(Dense(10, name="new_dense")) # will not be loaded -
# load weights from first model; will only affect the first layer, dense_1. -
model.load_weights(fname, by_name=True)
如何获得中间层的输出?
一个简单的方法是构建一个新模型输出你感兴趣的层。
-
from keras.models import Model -
model = ... # create the original model -
layer_name = 'my_layer' -
intermediate_layer_model = Model(inputs=model.input, -
outputs=model.get_layer(layer_name).output) -
intermediate_output = intermediate_layer_model.predict(data)
或者构建一个Keras函数返回给定输入的特定层的输出。
-
from keras import backend as K -
# with a Sequential model -
get_3rd_layer_output = K.function([model.layers[0].input], -
[model.layers[3].output]) -
layer_output = get_3rd_layer_output([X])[0]
类似的,可以直接构建Theano和TensorFlow函数。
注意,如果模型在训练和测试阶段表现不同(例如使用Dropout,BatchNormalization等),你需要将训练阶段标志传入函数。
-
get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()], -
[model.layers[3].output]) -
# output in test mode = 0 -
layer_output = get_3rd_layer_output([X, 0])[0] -
# output in train mode = 1 -
layer_output = get_3rd_layer_output([X, 1])[0]
数据集大于内存怎么办?
可以用model.train_on_batch(X, y)和model.test_on_batch(X, y)进行批次训练。
或者可以写一个生成器生成训练数据的批次然后使用方法model.fit_generator(data_generator, steps_per_epoch, epochs)
应用可参考https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py
如果验证损失不再下降如果打断训练?
可以使用EarlyStopping回调
-
from keras.callbacks import EarlyStopping -
early_stopping = EarlyStopping(monitor='val_loss', patience=2) -
model.fit(X, y, validation_split=0.2, callbacks=[early_stopping])
验证分割如何计算?
如果你设置model.fit申明validation_split为0.1,那么验证集使用最后10%的数据(如果在提取验证数据前没有将数据打乱)。同一验证集用于所有阶段(在同一fit调用)。
训练时打乱数据吗?
是的,如果model.fit中的shuffle设为True(默认值),训练数据在每个阶段会随机打乱。
如何在每个结算记录训练/验证损失/准确度?
model.fit方法返回一个History回调,有一个history属性包含了连续损失及其他度量的列表。
-
hist = model.fit(X, y, validation_split=0.2) -
print(hist.history)
如果冻结Keras的层?
冻结意味着把它排除在训练外,例如权重不会更新。这在细调模型中有用,或者对文本输入使用固定嵌入。
可以传递trainable申明(boolean)到层构建器设定层为non-trainable。
frozen_layer = Dense(32, trainable=False)
额外的,可以在实例化后设置一个层的trainable属性为True或者False。需要调用compile()才使其生效。
-
x = Input(shape=(32,)) -
layer = Dense(32) -
layer.trainable = False -
y = layer(x) -
frozen_model = Model(x, y) -
# in the model below, the weights of `layer` will not be updated during training -
frozen_model.compile(optimizer='rmsprop', loss='mse') -
layer.trainable = True -
trainable_model = Model(x, y) -
# with this model the weights of the layer will be updated during training -
# (which will also affect the above model since it uses the same layer instance) -
trainable_model.compile(optimizer='rmsprop', loss='mse') -
frozen_model.fit(data, labels) # this does NOT update the weights of `layer` -
trainable_model.fit(data, labels) # this updates the weights of `layer`
如何使用状态RNNs?
-
X # this is our input data, of shape (32, 21, 16) -
# we will feed it to our model in sequences of length 10 -
model = Sequential() -
model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True)) -
model.add(Dense(16, activation='softmax')) -
model.compile(optimizer='rmsprop', loss='categorical_crossentropy') -
# we train the network to predict the 11th timestep given the first 10: -
model.train_on_batch(X[:, :10, :], np.reshape(X[:, 10, :], (32, 16))) -
# the state of the network has changed. We can feed the follow-up sequences: -
model.train_on_batch(X[:, 10:20, :], np.reshape(X[:, 20, :], (32, 16))) -
# let's reset the states of the LSTM layer: -
model.reset_states() -
# another way to do it in this case: -
model.layers[0].reset_states()
如何在Keras中使用预训练模型?
我们提供以下图像分类模型的代码和预训练权重:
- Xception
- VGG16
- VGG19
- ResNet50
- Inception v3
可以使用keras.application模块导入。
-
from keras.applications.xception import Xception -
from keras.applications.vgg16 import VGG16 -
from keras.applications.vgg19 import VGG19 -
from keras.applications.resnet50 import ResNet50 -
from keras.applications.inception_v3 import InceptionV3 -
model = VGG16(weights='imagenet', include_top=True)
如何使用HDF5输入?
-
import h5py -
with h5py.File('input/file.hdf5', 'r') as f: -
X_data = f['X_data'] -
model.predict(X_data)
也可以使用keras.utils.io_utils中的HDF5Matrix类。
Keras设置文件储存在哪里?
默认的文件夹在$HOME/.keras/
如果因为没有权限创建上述文件夹,则可能在/tmp/.keras/
如何引用keras?
如果keras对您的研究有帮助,请在出版物中引用。BibTeX例子如下:
@misc{chollet2015keras,
title={Keras},
author={Chollet, Fran\c{c}ois and others},
year={2015},
publisher={GitHub},
howpublished={\url{https://github.com/fchollet/keras}},
}
如何在GPU上运行keras?
如果运行在TensorFlow后端上,代码会自动运行在检测到的GPU上。
如果运行在Theano后端上,可使用方法有:
1、使用Theano标志
THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py
'gpu'根据你的设备更改识别(例如gpu0, gpu1等等)
2、设置 .theanorc
3、在代码最前面手动设置theano.config.device,theano.config.floatX
-
import theano -
theano.config.device = 'gpu' -
theano.config.floatX = 'float32'
如何保存Keras模型?
不推荐用pickle或者cPickle来保存Keras模型。
可以使用model.save(filepath)将Keras模型保存到HDF5文件,包含:
-模型结构,可重建模型
-模型权重
-训练设置(损失、优化器)
-优化器状态,可恢复训练
然后使用keras.models.load_model(filepath)重新实例化模型。load_model会使用保存的训练设置重新编译模型。
例如:
-
from keras.models import load_model -
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' -
del model # deletes the existing model -
# returns a compiled model -
# identical to the previous one -
model = load_model('my_model.h5')
如果你只需要保存模型的结构,不需要权重和训练设置,则可以:
-
# save as JSON -
json_string = model.to_json() -
# save as YAML -
yaml_string = model.to_yaml()
生成的JSON/YAML文件具有可读性,如需要可以手工修改。
也可以从这个数据中重新构建新模型:
-
# model reconstruction from JSON: -
from keras.models import model_from_json -
model = model_from_json(json_string) -
# model reconstruction from YAML -
from keras.models import model_from_yaml -
model = model_from_yaml(yaml_string)
如果只需要保存模型的权重,可以在HDF5文件中使用以下代码。注意你需要已安装HDF5和h5py。
model.save_weights('my_model_weights.h5')
假定已实例化模型,然后可以将保存的权重加载到具有相同结构的模型中去
model.load_weights('my_model_weights.h5')
如果需要将权重加载到不同结构(有一些相同层),例如为细调或者转化学习,可以用层名称载入权重
model.load_weights('my_model_weights.h5', by_name=True)
举例如下:
-
""" -
Assume original model looks like this: -
model = Sequential() -
model.add(Dense(2, input_dim=3, name="dense_1")) -
model.add(Dense(3, name="dense_2")) -
... -
model.save_weights(fname) -
""" -
# new model -
model = Sequential() -
model.add(Dense(2, input_dim=3, name="dense_1")) # will be loaded -
model.add(Dense(10, name="new_dense")) # will not be loaded -
# load weights from first model; will only affect the first layer, dense_1. -
model.load_weights(fname, by_name=True)
如何获得中间层的输出?
一个简单的方法是构建一个新模型输出你感兴趣的层。
-
from keras.models import Model -
model = ... # create the original model -
layer_name = 'my_layer' -
intermediate_layer_model = Model(inputs=model.input, -
outputs=model.get_layer(layer_name).output) -
intermediate_output = intermediate_layer_model.predict(data)
或者构建一个Keras函数返回给定输入的特定层的输出。
-
from keras import backend as K -
# with a Sequential model -
get_3rd_layer_output = K.function([model.layers[0].input], -
[model.layers[3].output]) -
layer_output = get_3rd_layer_output([X])[0]
类似的,可以直接构建Theano和TensorFlow函数。
注意,如果模型在训练和测试阶段表现不同(例如使用Dropout,BatchNormalization等),你需要将训练阶段标志传入函数。
-
get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()], -
[model.layers[3].output]) -
# output in test mode = 0 -
layer_output = get_3rd_layer_output([X, 0])[0] -
# output in train mode = 1 -
layer_output = get_3rd_layer_output([X, 1])[0]
数据集大于内存怎么办?
可以用model.train_on_batch(X, y)和model.test_on_batch(X, y)进行批次训练。
或者可以写一个生成器生成训练数据的批次然后使用方法model.fit_generator(data_generator, steps_per_epoch, epochs)
应用可参考https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py
如果验证损失不再下降如果打断训练?
可以使用EarlyStopping回调
-
from keras.callbacks import EarlyStopping -
early_stopping = EarlyStopping(monitor='val_loss', patience=2) -
model.fit(X, y, validation_split=0.2, callbacks=[early_stopping])
验证分割如何计算?
如果你设置model.fit申明validation_split为0.1,那么验证集使用最后10%的数据(如果在提取验证数据前没有将数据打乱)。同一验证集用于所有阶段(在同一fit调用)。
训练时打乱数据吗?
是的,如果model.fit中的shuffle设为True(默认值),训练数据在每个阶段会随机打乱。
如何在每个结算记录训练/验证损失/准确度?
model.fit方法返回一个History回调,有一个history属性包含了连续损失及其他度量的列表。
-
hist = model.fit(X, y, validation_split=0.2) -
print(hist.history)
如果冻结Keras的层?
冻结意味着把它排除在训练外,例如权重不会更新。这在细调模型中有用,或者对文本输入使用固定嵌入。
可以传递trainable申明(boolean)到层构建器设定层为non-trainable。
frozen_layer = Dense(32, trainable=False)
额外的,可以在实例化后设置一个层的trainable属性为True或者False。需要调用compile()才使其生效。
-
x = Input(shape=(32,)) -
layer = Dense(32) -
layer.trainable = False -
y = layer(x) -
frozen_model = Model(x, y) -
# in the model below, the weights of `layer` will not be updated during training -
frozen_model.compile(optimizer='rmsprop', loss='mse') -
layer.trainable = True -
trainable_model = Model(x, y) -
# with this model the weights of the layer will be updated during training -
# (which will also affect the above model since it uses the same layer instance) -
trainable_model.compile(optimizer='rmsprop', loss='mse') -
frozen_model.fit(data, labels) # this does NOT update the weights of `layer` -
trainable_model.fit(data, labels) # this updates the weights of `layer`
如何使用状态RNNs?
-
X # this is our input data, of shape (32, 21, 16) -
# we will feed it to our model in sequences of length 10 -
model = Sequential() -
model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True)) -
model.add(Dense(16, activation='softmax')) -
model.compile(optimizer='rmsprop', loss='categorical_crossentropy') -
# we train the network to predict the 11th timestep given the first 10: -
model.train_on_batch(X[:, :10, :], np.reshape(X[:, 10, :], (32, 16))) -
# the state of the network has changed. We can feed the follow-up sequences: -
model.train_on_batch(X[:, 10:20, :], np.reshape(X[:, 20, :], (32, 16))) -
# let's reset the states of the LSTM layer: -
model.reset_states() -
# another way to do it in this case: -
model.layers[0].reset_states()
如何在Keras中使用预训练模型?
我们提供以下图像分类模型的代码和预训练权重:
- Xception
- VGG16
- VGG19
- ResNet50
- Inception v3
可以使用keras.application模块导入。
-
from keras.applications.xception import Xception -
from keras.applications.vgg16 import VGG16 -
from keras.applications.vgg19 import VGG19 -
from keras.applications.resnet50 import ResNet50 -
from keras.applications.inception_v3 import InceptionV3 -
model = VGG16(weights='imagenet', include_top=True)
如何使用HDF5输入?
-
import h5py -
with h5py.File('input/file.hdf5', 'r') as f: -
X_data = f['X_data'] -
model.predict(X_data)
也可以使用keras.utils.io_utils中的HDF5Matrix类。
Keras设置文件储存在哪里?
默认的文件夹在$HOME/.keras/
如果因为没有权限创建上述文件夹,则可能在/tmp/.keras/
如何引用keras?
如果keras对您的研究有帮助,请在出版物中引用。BibTeX例子如下:
@misc{chollet2015keras,
title={Keras},
author={Chollet, Fran\c{c}ois and others},
year={2015},
publisher={GitHub},
howpublished={\url{https://github.com/fchollet/keras}},
}
如何在GPU上运行keras?
如果运行在TensorFlow后端上,代码会自动运行在检测到的GPU上。
如果运行在Theano后端上,可使用方法有:
1、使用Theano标志
THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py
'gpu'根据你的设备更改识别(例如gpu0, gpu1等等)
2、设置 .theanorc
3、在代码最前面手动设置theano.config.device,theano.config.floatX
-
import theano -
theano.config.device = 'gpu' -
theano.config.floatX = 'float32'
如何保存Keras模型?
不推荐用pickle或者cPickle来保存Keras模型。
可以使用model.save(filepath)将Keras模型保存到HDF5文件,包含:
-模型结构,可重建模型
-模型权重
-训练设置(损失、优化器)
-优化器状态,可恢复训练
然后使用keras.models.load_model(filepath)重新实例化模型。load_model会使用保存的训练设置重新编译模型。
例如:
-
from keras.models import load_model -
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' -
del model # deletes the existing model -
# returns a compiled model -
# identical to the previous one -
model = load_model('my_model.h5')
如果你只需要保存模型的结构,不需要权重和训练设置,则可以:
-
# save as JSON -
json_string = model.to_json() -
# save as YAML -
yaml_string = model.to_yaml()
生成的JSON/YAML文件具有可读性,如需要可以手工修改。
也可以从这个数据中重新构建新模型:
-
# model reconstruction from JSON: -
from keras.models import model_from_json -
model = model_from_json(json_string) -
# model reconstruction from YAML -
from keras.models import model_from_yaml -
model = model_from_yaml(yaml_string)
如果只需要保存模型的权重,可以在HDF5文件中使用以下代码。注意你需要已安装HDF5和h5py。
model.save_weights('my_model_weights.h5')
假定已实例化模型,然后可以将保存的权重加载到具有相同结构的模型中去
model.load_weights('my_model_weights.h5')
如果需要将权重加载到不同结构(有一些相同层),例如为细调或者转化学习,可以用层名称载入权重
model.load_weights('my_model_weights.h5', by_name=True)
举例如下:
-
""" -
Assume original model looks like this: -
model = Sequential() -
model.add(Dense(2, input_dim=3, name="dense_1")) -
model.add(Dense(3, name="dense_2")) -
... -
model.save_weights(fname) -
""" -
# new model -
model = Sequential() -
model.add(Dense(2, input_dim=3, name="dense_1")) # will be loaded -
model.add(Dense(10, name="new_dense")) # will not be loaded -
# load weights from first model; will only affect the first layer, dense_1. -
model.load_weights(fname, by_name=True)
如何获得中间层的输出?
一个简单的方法是构建一个新模型输出你感兴趣的层。
-
from keras.models import Model -
model = ... # create the original model -
layer_name = 'my_layer' -
intermediate_layer_model = Model(inputs=model.input, -
outputs=model.get_layer(layer_name).output) -
intermediate_output = intermediate_layer_model.predict(data)
或者构建一个Keras函数返回给定输入的特定层的输出。
-
from keras import backend as K -
# with a Sequential model -
get_3rd_layer_output = K.function([model.layers[0].input], -
[model.layers[3].output]) -
layer_output = get_3rd_layer_output([X])[0]
类似的,可以直接构建Theano和TensorFlow函数。
注意,如果模型在训练和测试阶段表现不同(例如使用Dropout,BatchNormalization等),你需要将训练阶段标志传入函数。
-
get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()], -
[model.layers[3].output]) -
# output in test mode = 0 -
layer_output = get_3rd_layer_output([X, 0])[0] -
# output in train mode = 1 -
layer_output = get_3rd_layer_output([X, 1])[0]
数据集大于内存怎么办?
可以用model.train_on_batch(X, y)和model.test_on_batch(X, y)进行批次训练。
或者可以写一个生成器生成训练数据的批次然后使用方法model.fit_generator(data_generator, steps_per_epoch, epochs)
应用可参考https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py
如果验证损失不再下降如果打断训练?
可以使用EarlyStopping回调
-
from keras.callbacks import EarlyStopping -
early_stopping = EarlyStopping(monitor='val_loss', patience=2) -
model.fit(X, y, validation_split=0.2, callbacks=[early_stopping])
验证分割如何计算?
如果你设置model.fit申明validation_split为0.1,那么验证集使用最后10%的数据(如果在提取验证数据前没有将数据打乱)。同一验证集用于所有阶段(在同一fit调用)。
训练时打乱数据吗?
是的,如果model.fit中的shuffle设为True(默认值),训练数据在每个阶段会随机打乱。
如何在每个结算记录训练/验证损失/准确度?
model.fit方法返回一个History回调,有一个history属性包含了连续损失及其他度量的列表。
-
hist = model.fit(X, y, validation_split=0.2) -
print(hist.history)
如果冻结Keras的层?
冻结意味着把它排除在训练外,例如权重不会更新。这在细调模型中有用,或者对文本输入使用固定嵌入。
可以传递trainable申明(boolean)到层构建器设定层为non-trainable。
frozen_layer = Dense(32, trainable=False)
额外的,可以在实例化后设置一个层的trainable属性为True或者False。需要调用compile()才使其生效。
-
x = Input(shape=(32,)) -
layer = Dense(32) -
layer.trainable = False -
y = layer(x) -
frozen_model = Model(x, y) -
# in the model below, the weights of `layer` will not be updated during training -
frozen_model.compile(optimizer='rmsprop', loss='mse') -
layer.trainable = True -
trainable_model = Model(x, y) -
# with this model the weights of the layer will be updated during training -
# (which will also affect the above model since it uses the same layer instance) -
trainable_model.compile(optimizer='rmsprop', loss='mse') -
frozen_model.fit(data, labels) # this does NOT update the weights of `layer` -
trainable_model.fit(data, labels) # this updates the weights of `layer`
如何使用状态RNNs?
-
X # this is our input data, of shape (32, 21, 16) -
# we will feed it to our model in sequences of length 10 -
model = Sequential() -
model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True)) -
model.add(Dense(16, activation='softmax')) -
model.compile(optimizer='rmsprop', loss='categorical_crossentropy') -
# we train the network to predict the 11th timestep given the first 10: -
model.train_on_batch(X[:, :10, :], np.reshape(X[:, 10, :], (32, 16))) -
# the state of the network has changed. We can feed the follow-up sequences: -
model.train_on_batch(X[:, 10:20, :], np.reshape(X[:, 20, :], (32, 16))) -
# let's reset the states of the LSTM layer: -
model.reset_states() -
# another way to do it in this case: -
model.layers[0].reset_states()
如何在Keras中使用预训练模型?
我们提供以下图像分类模型的代码和预训练权重:
- Xception
- VGG16
- VGG19
- ResNet50
- Inception v3
可以使用keras.application模块导入。
-
from keras.applications.xception import Xception -
from keras.applications.vgg16 import VGG16 -
from keras.applications.vgg19 import VGG19 -
from keras.applications.resnet50 import ResNet50 -
from keras.applications.inception_v3 import InceptionV3 -
model = VGG16(weights='imagenet', include_top=True)
如何使用HDF5输入?
-
import h5py -
with h5py.File('input/file.hdf5', 'r') as f: -
X_data = f['X_data'] -
model.predict(X_data)
也可以使用keras.utils.io_utils中的HDF5Matrix类。
Keras设置文件储存在哪里?
默认的文件夹在$HOME/.keras/
如果因为没有权限创建上述文件夹,则可能在/tmp/.keras/
来源:CSDN
作者:WK785456510
链接:https://blog.csdn.net/WK785456510/article/details/104050223