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

 

 
 
  1. import theano

  2. theano.config.device = 'gpu'

  3. theano.config.floatX = 'float32'

 

如何保存Keras模型?

不推荐用pickle或者cPickle来保存Keras模型。

可以使用model.save(filepath)将Keras模型保存到HDF5文件,包含:

-模型结构,可重建模型

-模型权重

-训练设置(损失、优化器)

-优化器状态,可恢复训练

然后使用keras.models.load_model(filepath)重新实例化模型。load_model会使用保存的训练设置重新编译模型。

例如:

 

 
  1. from keras.models import load_model

  2.  
  3. model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'

  4. del model # deletes the existing model

  5.  
  6. # returns a compiled model

  7. # identical to the previous one

  8. model = load_model('my_model.h5')

 

如果你只需要保存模型的结构,不需要权重和训练设置,则可以:

 

 
  1. # save as JSON

  2. json_string = model.to_json()

  3.  
  4. # save as YAML

  5. yaml_string = model.to_yaml()


生成的JSON/YAML文件具有可读性,如需要可以手工修改。

也可以从这个数据中重新构建新模型:

 

 
  1. # model reconstruction from JSON:

  2. from keras.models import model_from_json

  3. model = model_from_json(json_string)

  4.  
  5. # model reconstruction from YAML

  6. from keras.models import model_from_yaml

  7. 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)


举例如下:

 

 
  1. """

  2. Assume original model looks like this:

  3. model = Sequential()

  4. model.add(Dense(2, input_dim=3, name="dense_1"))

  5. model.add(Dense(3, name="dense_2"))

  6. ...

  7. model.save_weights(fname)

  8. """

  9.  
  10. # new model

  11. model = Sequential()

  12. model.add(Dense(2, input_dim=3, name="dense_1")) # will be loaded

  13. model.add(Dense(10, name="new_dense")) # will not be loaded

  14.  
  15. # load weights from first model; will only affect the first layer, dense_1.

  16. model.load_weights(fname, by_name=True)

 

如何获得中间层的输出?

一个简单的方法是构建一个新模型输出你感兴趣的层。

 

 
  1. from keras.models import Model

  2.  
  3. model = ... # create the original model

  4.  
  5. layer_name = 'my_layer'

  6. intermediate_layer_model = Model(inputs=model.input,

  7. outputs=model.get_layer(layer_name).output)

  8. intermediate_output = intermediate_layer_model.predict(data)


或者构建一个Keras函数返回给定输入的特定层的输出。

 

 
  1. from keras import backend as K

  2.  
  3. # with a Sequential model

  4. get_3rd_layer_output = K.function([model.layers[0].input],

  5. [model.layers[3].output])

  6. layer_output = get_3rd_layer_output([X])[0]

 

类似的,可以直接构建Theano和TensorFlow函数。

注意,如果模型在训练和测试阶段表现不同(例如使用Dropout,BatchNormalization等),你需要将训练阶段标志传入函数。

 

 
  1. get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()],

  2. [model.layers[3].output])

  3.  
  4. # output in test mode = 0

  5. layer_output = get_3rd_layer_output([X, 0])[0]

  6.  
  7. # output in train mode = 1

  8. 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回调

 

 
  1. from keras.callbacks import EarlyStopping

  2. early_stopping = EarlyStopping(monitor='val_loss', patience=2)

  3. 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属性包含了连续损失及其他度量的列表。

 

 
  1. hist = model.fit(X, y, validation_split=0.2)

  2. print(hist.history)

 

如果冻结Keras的层?

冻结意味着把它排除在训练外,例如权重不会更新。这在细调模型中有用,或者对文本输入使用固定嵌入。

可以传递trainable申明(boolean)到层构建器设定层为non-trainable。

 

frozen_layer = Dense(32, trainable=False)


额外的,可以在实例化后设置一个层的trainable属性为True或者False。需要调用compile()才使其生效。

 

 
  1. x = Input(shape=(32,))

  2. layer = Dense(32)

  3. layer.trainable = False

  4. y = layer(x)

  5.  
  6. frozen_model = Model(x, y)

  7. # in the model below, the weights of `layer` will not be updated during training

  8. frozen_model.compile(optimizer='rmsprop', loss='mse')

  9.  
  10. layer.trainable = True

  11. trainable_model = Model(x, y)

  12. # with this model the weights of the layer will be updated during training

  13. # (which will also affect the above model since it uses the same layer instance)

  14. trainable_model.compile(optimizer='rmsprop', loss='mse')

  15.  
  16. frozen_model.fit(data, labels) # this does NOT update the weights of `layer`

  17. trainable_model.fit(data, labels) # this updates the weights of `layer`


如何使用状态RNNs?

 

 
  1. X # this is our input data, of shape (32, 21, 16)

  2. # we will feed it to our model in sequences of length 10

  3.  
  4. model = Sequential()

  5. model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True))

  6. model.add(Dense(16, activation='softmax'))

  7.  
  8. model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

  9.  
  10. # we train the network to predict the 11th timestep given the first 10:

  11. model.train_on_batch(X[:, :10, :], np.reshape(X[:, 10, :], (32, 16)))

  12.  
  13. # the state of the network has changed. We can feed the follow-up sequences:

  14. model.train_on_batch(X[:, 10:20, :], np.reshape(X[:, 20, :], (32, 16)))

  15.  
  16. # let's reset the states of the LSTM layer:

  17. model.reset_states()

  18.  
  19. # another way to do it in this case:

  20. model.layers[0].reset_states()


如何在Keras中使用预训练模型?

我们提供以下图像分类模型的代码和预训练权重:

 

  • Xception
  • VGG16
  • VGG19
  • ResNet50
  • Inception v3

可以使用keras.application模块导入。

 

 

 
  1. from keras.applications.xception import Xception

  2. from keras.applications.vgg16 import VGG16

  3. from keras.applications.vgg19 import VGG19

  4. from keras.applications.resnet50 import ResNet50

  5. from keras.applications.inception_v3 import InceptionV3

  6.  
  7. model = VGG16(weights='imagenet', include_top=True)

 

如何使用HDF5输入?

 

 
  1. import h5py

  2. with h5py.File('input/file.hdf5', 'r') as f:

  3. X_data = f['X_data']

  4. 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

 

 
 
  1. import theano

  2. theano.config.device = 'gpu'

  3. theano.config.floatX = 'float32'

 

如何保存Keras模型?

不推荐用pickle或者cPickle来保存Keras模型。

可以使用model.save(filepath)将Keras模型保存到HDF5文件,包含:

-模型结构,可重建模型

-模型权重

-训练设置(损失、优化器)

-优化器状态,可恢复训练

然后使用keras.models.load_model(filepath)重新实例化模型。load_model会使用保存的训练设置重新编译模型。

例如:

 

 
  1. from keras.models import load_model

  2.  
  3. model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'

  4. del model # deletes the existing model

  5.  
  6. # returns a compiled model

  7. # identical to the previous one

  8. model = load_model('my_model.h5')

 

如果你只需要保存模型的结构,不需要权重和训练设置,则可以:

 

 
  1. # save as JSON

  2. json_string = model.to_json()

  3.  
  4. # save as YAML

  5. yaml_string = model.to_yaml()


生成的JSON/YAML文件具有可读性,如需要可以手工修改。

也可以从这个数据中重新构建新模型:

 

 
  1. # model reconstruction from JSON:

  2. from keras.models import model_from_json

  3. model = model_from_json(json_string)

  4.  
  5. # model reconstruction from YAML

  6. from keras.models import model_from_yaml

  7. 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)


举例如下:

 

 
  1. """

  2. Assume original model looks like this:

  3. model = Sequential()

  4. model.add(Dense(2, input_dim=3, name="dense_1"))

  5. model.add(Dense(3, name="dense_2"))

  6. ...

  7. model.save_weights(fname)

  8. """

  9.  
  10. # new model

  11. model = Sequential()

  12. model.add(Dense(2, input_dim=3, name="dense_1")) # will be loaded

  13. model.add(Dense(10, name="new_dense")) # will not be loaded

  14.  
  15. # load weights from first model; will only affect the first layer, dense_1.

  16. model.load_weights(fname, by_name=True)

 

如何获得中间层的输出?

一个简单的方法是构建一个新模型输出你感兴趣的层。

 

 
  1. from keras.models import Model

  2.  
  3. model = ... # create the original model

  4.  
  5. layer_name = 'my_layer'

  6. intermediate_layer_model = Model(inputs=model.input,

  7. outputs=model.get_layer(layer_name).output)

  8. intermediate_output = intermediate_layer_model.predict(data)


或者构建一个Keras函数返回给定输入的特定层的输出。

 

 
  1. from keras import backend as K

  2.  
  3. # with a Sequential model

  4. get_3rd_layer_output = K.function([model.layers[0].input],

  5. [model.layers[3].output])

  6. layer_output = get_3rd_layer_output([X])[0]

 

类似的,可以直接构建Theano和TensorFlow函数。

注意,如果模型在训练和测试阶段表现不同(例如使用Dropout,BatchNormalization等),你需要将训练阶段标志传入函数。

 

 
  1. get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()],

  2. [model.layers[3].output])

  3.  
  4. # output in test mode = 0

  5. layer_output = get_3rd_layer_output([X, 0])[0]

  6.  
  7. # output in train mode = 1

  8. 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回调

 

 
  1. from keras.callbacks import EarlyStopping

  2. early_stopping = EarlyStopping(monitor='val_loss', patience=2)

  3. 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属性包含了连续损失及其他度量的列表。

 

 
  1. hist = model.fit(X, y, validation_split=0.2)

  2. print(hist.history)

 

如果冻结Keras的层?

冻结意味着把它排除在训练外,例如权重不会更新。这在细调模型中有用,或者对文本输入使用固定嵌入。

可以传递trainable申明(boolean)到层构建器设定层为non-trainable。

 

frozen_layer = Dense(32, trainable=False)


额外的,可以在实例化后设置一个层的trainable属性为True或者False。需要调用compile()才使其生效。

 

 
  1. x = Input(shape=(32,))

  2. layer = Dense(32)

  3. layer.trainable = False

  4. y = layer(x)

  5.  
  6. frozen_model = Model(x, y)

  7. # in the model below, the weights of `layer` will not be updated during training

  8. frozen_model.compile(optimizer='rmsprop', loss='mse')

  9.  
  10. layer.trainable = True

  11. trainable_model = Model(x, y)

  12. # with this model the weights of the layer will be updated during training

  13. # (which will also affect the above model since it uses the same layer instance)

  14. trainable_model.compile(optimizer='rmsprop', loss='mse')

  15.  
  16. frozen_model.fit(data, labels) # this does NOT update the weights of `layer`

  17. trainable_model.fit(data, labels) # this updates the weights of `layer`


如何使用状态RNNs?

 

 
  1. X # this is our input data, of shape (32, 21, 16)

  2. # we will feed it to our model in sequences of length 10

  3.  
  4. model = Sequential()

  5. model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True))

  6. model.add(Dense(16, activation='softmax'))

  7.  
  8. model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

  9.  
  10. # we train the network to predict the 11th timestep given the first 10:

  11. model.train_on_batch(X[:, :10, :], np.reshape(X[:, 10, :], (32, 16)))

  12.  
  13. # the state of the network has changed. We can feed the follow-up sequences:

  14. model.train_on_batch(X[:, 10:20, :], np.reshape(X[:, 20, :], (32, 16)))

  15.  
  16. # let's reset the states of the LSTM layer:

  17. model.reset_states()

  18.  
  19. # another way to do it in this case:

  20. model.layers[0].reset_states()


如何在Keras中使用预训练模型?

我们提供以下图像分类模型的代码和预训练权重:

 

  • Xception
  • VGG16
  • VGG19
  • ResNet50
  • Inception v3

可以使用keras.application模块导入。

 

 

 
  1. from keras.applications.xception import Xception

  2. from keras.applications.vgg16 import VGG16

  3. from keras.applications.vgg19 import VGG19

  4. from keras.applications.resnet50 import ResNet50

  5. from keras.applications.inception_v3 import InceptionV3

  6.  
  7. model = VGG16(weights='imagenet', include_top=True)

 

如何使用HDF5输入?

 

 
  1. import h5py

  2. with h5py.File('input/file.hdf5', 'r') as f:

  3. X_data = f['X_data']

  4. 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

 

 
 
  1. import theano

  2. theano.config.device = 'gpu'

  3. theano.config.floatX = 'float32'

 

如何保存Keras模型?

不推荐用pickle或者cPickle来保存Keras模型。

可以使用model.save(filepath)将Keras模型保存到HDF5文件,包含:

-模型结构,可重建模型

-模型权重

-训练设置(损失、优化器)

-优化器状态,可恢复训练

然后使用keras.models.load_model(filepath)重新实例化模型。load_model会使用保存的训练设置重新编译模型。

例如:

 

 
  1. from keras.models import load_model

  2.  
  3. model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'

  4. del model # deletes the existing model

  5.  
  6. # returns a compiled model

  7. # identical to the previous one

  8. model = load_model('my_model.h5')

 

如果你只需要保存模型的结构,不需要权重和训练设置,则可以:

 

 
  1. # save as JSON

  2. json_string = model.to_json()

  3.  
  4. # save as YAML

  5. yaml_string = model.to_yaml()


生成的JSON/YAML文件具有可读性,如需要可以手工修改。

也可以从这个数据中重新构建新模型:

 

 
  1. # model reconstruction from JSON:

  2. from keras.models import model_from_json

  3. model = model_from_json(json_string)

  4.  
  5. # model reconstruction from YAML

  6. from keras.models import model_from_yaml

  7. 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)


举例如下:

 

 
  1. """

  2. Assume original model looks like this:

  3. model = Sequential()

  4. model.add(Dense(2, input_dim=3, name="dense_1"))

  5. model.add(Dense(3, name="dense_2"))

  6. ...

  7. model.save_weights(fname)

  8. """

  9.  
  10. # new model

  11. model = Sequential()

  12. model.add(Dense(2, input_dim=3, name="dense_1")) # will be loaded

  13. model.add(Dense(10, name="new_dense")) # will not be loaded

  14.  
  15. # load weights from first model; will only affect the first layer, dense_1.

  16. model.load_weights(fname, by_name=True)

 

如何获得中间层的输出?

一个简单的方法是构建一个新模型输出你感兴趣的层。

 

 
  1. from keras.models import Model

  2.  
  3. model = ... # create the original model

  4.  
  5. layer_name = 'my_layer'

  6. intermediate_layer_model = Model(inputs=model.input,

  7. outputs=model.get_layer(layer_name).output)

  8. intermediate_output = intermediate_layer_model.predict(data)


或者构建一个Keras函数返回给定输入的特定层的输出。

 

 
  1. from keras import backend as K

  2.  
  3. # with a Sequential model

  4. get_3rd_layer_output = K.function([model.layers[0].input],

  5. [model.layers[3].output])

  6. layer_output = get_3rd_layer_output([X])[0]

 

类似的,可以直接构建Theano和TensorFlow函数。

注意,如果模型在训练和测试阶段表现不同(例如使用Dropout,BatchNormalization等),你需要将训练阶段标志传入函数。

 

 
  1. get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()],

  2. [model.layers[3].output])

  3.  
  4. # output in test mode = 0

  5. layer_output = get_3rd_layer_output([X, 0])[0]

  6.  
  7. # output in train mode = 1

  8. 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回调

 

 
  1. from keras.callbacks import EarlyStopping

  2. early_stopping = EarlyStopping(monitor='val_loss', patience=2)

  3. 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属性包含了连续损失及其他度量的列表。

 

 
  1. hist = model.fit(X, y, validation_split=0.2)

  2. print(hist.history)

 

如果冻结Keras的层?

冻结意味着把它排除在训练外,例如权重不会更新。这在细调模型中有用,或者对文本输入使用固定嵌入。

可以传递trainable申明(boolean)到层构建器设定层为non-trainable。

 

frozen_layer = Dense(32, trainable=False)


额外的,可以在实例化后设置一个层的trainable属性为True或者False。需要调用compile()才使其生效。

 

 
  1. x = Input(shape=(32,))

  2. layer = Dense(32)

  3. layer.trainable = False

  4. y = layer(x)

  5.  
  6. frozen_model = Model(x, y)

  7. # in the model below, the weights of `layer` will not be updated during training

  8. frozen_model.compile(optimizer='rmsprop', loss='mse')

  9.  
  10. layer.trainable = True

  11. trainable_model = Model(x, y)

  12. # with this model the weights of the layer will be updated during training

  13. # (which will also affect the above model since it uses the same layer instance)

  14. trainable_model.compile(optimizer='rmsprop', loss='mse')

  15.  
  16. frozen_model.fit(data, labels) # this does NOT update the weights of `layer`

  17. trainable_model.fit(data, labels) # this updates the weights of `layer`


如何使用状态RNNs?

 

 
  1. X # this is our input data, of shape (32, 21, 16)

  2. # we will feed it to our model in sequences of length 10

  3.  
  4. model = Sequential()

  5. model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True))

  6. model.add(Dense(16, activation='softmax'))

  7.  
  8. model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

  9.  
  10. # we train the network to predict the 11th timestep given the first 10:

  11. model.train_on_batch(X[:, :10, :], np.reshape(X[:, 10, :], (32, 16)))

  12.  
  13. # the state of the network has changed. We can feed the follow-up sequences:

  14. model.train_on_batch(X[:, 10:20, :], np.reshape(X[:, 20, :], (32, 16)))

  15.  
  16. # let's reset the states of the LSTM layer:

  17. model.reset_states()

  18.  
  19. # another way to do it in this case:

  20. model.layers[0].reset_states()


如何在Keras中使用预训练模型?

我们提供以下图像分类模型的代码和预训练权重:

 

  • Xception
  • VGG16
  • VGG19
  • ResNet50
  • Inception v3

可以使用keras.application模块导入。

 

 

 
  1. from keras.applications.xception import Xception

  2. from keras.applications.vgg16 import VGG16

  3. from keras.applications.vgg19 import VGG19

  4. from keras.applications.resnet50 import ResNet50

  5. from keras.applications.inception_v3 import InceptionV3

  6.  
  7. model = VGG16(weights='imagenet', include_top=True)

 

如何使用HDF5输入?

 

 
  1. import h5py

  2. with h5py.File('input/file.hdf5', 'r') as f:

  3. X_data = f['X_data']

  4. model.predict(X_data)


也可以使用keras.utils.io_utils中的HDF5Matrix类。

Keras设置文件储存在哪里?

默认的文件夹在$HOME/.keras/

如果因为没有权限创建上述文件夹,则可能在/tmp/.keras/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值