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/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章