本文整理汇总了Python中keras.models.Sequential.from_config方法的典型用法代码示例。如果您正苦于以下问题:Python Sequential.from_config方法的具体用法?Python Sequential.from_config怎么用?Python Sequential.from_config使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.models.Sequential
的用法示例。
在下文中一共展示了Sequential.from_config方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_nested_sequential
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_nested_sequential(in_tmpdir):
(x_train, y_train), (x_test, y_test) = _get_test_data()
inner = Sequential()
inner.add(Dense(num_hidden, input_shape=(input_dim,)))
inner.add(Activation('relu'))
inner.add(Dense(num_class))
middle = Sequential()
middle.add(inner)
model = Sequential()
model.add(middle)
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=2, validation_split=0.1)
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=0)
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, shuffle=False)
model.train_on_batch(x_train[:32], y_train[:32])
loss = model.evaluate(x_test, y_test, verbose=0)
model.predict(x_test, verbose=0)
model.predict_classes(x_test, verbose=0)
model.predict_proba(x_test, verbose=0)
fname = 'test_nested_sequential_temp.h5'
model.save_weights(fname, overwrite=True)
inner = Sequential()
inner.add(Dense(num_hidden, input_shape=(input_dim,)))
inner.add(Activation('relu'))
inner.add(Dense(num_class))
middle = Sequential()
middle.add(inner)
model = Sequential()
model.add(middle)
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.load_weights(fname)
os.remove(fname)
nloss = model.evaluate(x_test, y_test, verbose=0)
assert(loss == nloss)
# test serialization
config = model.get_config()
Sequential.from_config(config)
model.summary()
json_str = model.to_json()
model_from_json(json_str)
yaml_str = model.to_yaml()
model_from_yaml(yaml_str)
示例2: test_merge_sum
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_merge_sum():
(X_train, y_train), (X_test, y_test) = _get_test_data()
left = Sequential()
left.add(Dense(nb_hidden, input_shape=(input_dim,)))
left.add(Activation('relu'))
right = Sequential()
right.add(Dense(nb_hidden, input_shape=(input_dim,)))
right.add(Activation('relu'))
model = Sequential()
model.add(Merge([left, right], mode='sum'))
model.add(Dense(nb_class))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.fit([X_train, X_train], y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, validation_data=([X_test, X_test], y_test))
model.fit([X_train, X_train], y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, validation_split=0.1)
model.fit([X_train, X_train], y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
model.fit([X_train, X_train], y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0, shuffle=False)
loss = model.evaluate([X_test, X_test], y_test, verbose=0)
model.predict([X_test, X_test], verbose=0)
model.predict_classes([X_test, X_test], verbose=0)
model.predict_proba([X_test, X_test], verbose=0)
# test weight saving
fname = 'test_merge_sum_temp.h5'
model.save_weights(fname, overwrite=True)
left = Sequential()
left.add(Dense(nb_hidden, input_shape=(input_dim,)))
left.add(Activation('relu'))
right = Sequential()
right.add(Dense(nb_hidden, input_shape=(input_dim,)))
right.add(Activation('relu'))
model = Sequential()
model.add(Merge([left, right], mode='sum'))
model.add(Dense(nb_class))
model.add(Activation('softmax'))
model.load_weights(fname)
os.remove(fname)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
nloss = model.evaluate([X_test, X_test], y_test, verbose=0)
assert(loss == nloss)
# test serialization
config = model.get_config()
Sequential.from_config(config)
model.summary()
json_str = model.to_json()
model_from_json(json_str)
yaml_str = model.to_yaml()
model_from_yaml(yaml_str)
示例3: test_temporal_classification
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_temporal_classification():
'''
Classify temporal sequences of float numbers
of length 3 into 2 classes using
single layer of GRU units and softmax applied
to the last activations of the units
'''
np.random.seed(1337)
(x_train, y_train), (x_test, y_test) = get_test_data(num_train=200,
num_test=20,
input_shape=(3, 4),
classification=True,
num_classes=2)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
model = Sequential()
model.add(layers.GRU(8,
input_shape=(x_train.shape[1], x_train.shape[2])))
model.add(layers.Dense(y_train.shape[-1], activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.summary()
history = model.fit(x_train, y_train, epochs=4, batch_size=10,
validation_data=(x_test, y_test),
verbose=0)
assert(history.history['acc'][-1] >= 0.8)
config = model.get_config()
model = Sequential.from_config(config)
示例4: test_image_classification
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_image_classification():
np.random.seed(1337)
input_shape = (16, 16, 3)
(x_train, y_train), (x_test, y_test) = get_test_data(num_train=500,
num_test=200,
input_shape=input_shape,
classification=True,
num_classes=4)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
model = Sequential([
layers.Conv2D(filters=8, kernel_size=3,
activation='relu',
input_shape=input_shape),
layers.MaxPooling2D(pool_size=2),
layers.Conv2D(filters=4, kernel_size=(3, 3),
activation='relu', padding='same'),
layers.GlobalAveragePooling2D(),
layers.Dense(y_test.shape[-1], activation='softmax')
])
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.summary()
history = model.fit(x_train, y_train, epochs=10, batch_size=16,
validation_data=(x_test, y_test),
verbose=0)
assert history.history['val_acc'][-1] > 0.75
config = model.get_config()
model = Sequential.from_config(config)
示例5: test_recursive
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_recursive():
# test layer-like API
graph = Graph()
graph.add_input(name='input1', input_shape=(32,))
graph.add_node(Dense(16), name='dense1', input='input1')
graph.add_node(Dense(4), name='dense2', input='input1')
graph.add_node(Dense(4), name='dense3', input='dense1')
graph.add_output(name='output1', inputs=['dense2', 'dense3'],
merge_mode='sum')
seq = Sequential()
seq.add(Dense(32, input_shape=(32,)))
seq.add(graph)
seq.add(Dense(4))
seq.compile('rmsprop', 'mse')
seq.fit(X_train_graph, y_train_graph, batch_size=10, nb_epoch=10)
loss = seq.evaluate(X_test_graph, y_test_graph)
# test serialization
config = seq.get_config()
new_graph = Sequential.from_config(config)
seq.summary()
json_str = seq.to_json()
new_graph = model_from_json(json_str)
yaml_str = seq.to_yaml()
new_graph = model_from_yaml(yaml_str)
示例6: test_vector_classification
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_vector_classification():
'''
Classify random float vectors into 2 classes with logistic regression
using 2 layer neural network with ReLU hidden units.
'''
(x_train, y_train), (x_test, y_test) = get_test_data(num_train=500,
num_test=200,
input_shape=(20,),
classification=True,
num_classes=2)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# Test with Sequential API
model = Sequential([
layers.Dense(16, input_shape=(x_train.shape[-1],), activation='relu'),
layers.Dense(8),
layers.Activation('relu'),
layers.Dense(y_train.shape[-1], activation='softmax')
])
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.summary()
history = model.fit(x_train, y_train, epochs=15, batch_size=16,
validation_data=(x_test, y_test),
verbose=0)
assert(history.history['val_acc'][-1] > 0.8)
config = model.get_config()
model = Sequential.from_config(config)
示例7: test_nested_sequential
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_nested_sequential():
(X_train, y_train), (X_test, y_test) = _get_test_data()
inner = Sequential()
inner.add(Dense(nb_hidden, input_shape=(input_dim,)))
inner.add(Activation("relu"))
inner.add(Dense(nb_class))
middle = Sequential()
middle.add(inner)
model = Sequential()
model.add(middle)
model.add(Activation("softmax"))
model.compile(loss="categorical_crossentropy", optimizer="rmsprop")
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, y_test))
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=2, validation_split=0.1)
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, shuffle=False)
model.train_on_batch(X_train[:32], y_train[:32])
loss = model.evaluate(X_test, y_test, verbose=0)
model.predict(X_test, verbose=0)
model.predict_classes(X_test, verbose=0)
model.predict_proba(X_test, verbose=0)
fname = "test_nested_sequential_temp.h5"
model.save_weights(fname, overwrite=True)
inner = Sequential()
inner.add(Dense(nb_hidden, input_shape=(input_dim,)))
inner.add(Activation("relu"))
inner.add(Dense(nb_class))
middle = Sequential()
middle.add(inner)
model = Sequential()
model.add(middle)
model.add(Activation("softmax"))
model.compile(loss="categorical_crossentropy", optimizer="rmsprop")
model.load_weights(fname)
os.remove(fname)
nloss = model.evaluate(X_test, y_test, verbose=0)
assert loss == nloss
# test serialization
config = model.get_config()
new_model = Sequential.from_config(config)
model.summary()
json_str = model.to_json()
new_model = model_from_json(json_str)
yaml_str = model.to_yaml()
new_model = model_from_yaml(yaml_str)
示例8: clone_model
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def clone_model(model, custom_objects={}):
config = model.get_config()
try:
clone = Sequential.from_config(config, custom_objects)
except:
clone = Model.from_config(config, custom_objects)
clone.set_weights(model.get_weights())
return clone
示例9: create_duplicate_model
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def create_duplicate_model(model):
"""Create a duplicate keras model."""
new_model = Sequential.from_config(model.get_config())
new_model.set_weights(copy.deepcopy(model.get_weights()))
new_model.compile(loss=model.loss,optimizer=model.optimizer)
return new_model
示例10: __init__
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def __init__ (self, model, max_memory=2000, discount=0.7, unfreeze_count=5):
self.max_memory = max_memory
self.discount = discount
self.unfreeze_count = unfreeze_count
self.memory = []
self.buffer = []
self.frozen_model = Sequential.from_config (model.get_config ())
self.frozen_model.compile (sgd(lr=.01), "mse")
示例11: __init__
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def __init__ (self, model, max_memory, discount, unfreeze_count, num_actions):
self.max_memory = max_memory
self.discount = discount
self.unfreeze_count = unfreeze_count
self.num_actions = num_actions
self.memory = list ()
# TODO dont assume sequential model
# note taining algo has no affect because frozen model is never trianed
self.frozen_model = Sequential.from_config (model.get_config ())
self.frozen_model.compile (sgd(lr=.01), "mse")
示例12: clone_model
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def clone_model(model, custom_objects={}):
if len(custom_objects) > 0:
warnings.warn('Due to an API problem with Keras, custom_objects is currently ignored. Sorry about that.')
config = model.get_config()
try:
# TODO: re-enable custom_objects
clone = Sequential.from_config(config)
except:
# TODO: re-enable custom_objects
clone = Model.from_config(config)
clone.set_weights(model.get_weights())
return clone
示例13: test_merge_overlap
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def test_merge_overlap():
(X_train, y_train), (X_test, y_test) = _get_test_data()
left = Sequential()
left.add(Dense(nb_hidden, input_shape=(input_dim,)))
left.add(Activation('relu'))
model = Sequential()
model.add(Merge([left, left], mode='sum'))
model.add(Dense(nb_class))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, y_test))
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=2, validation_split=0.1)
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=0)
model.fit(X_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, shuffle=False)
model.train_on_batch(X_train[:32], y_train[:32])
loss = model.evaluate(X_test, y_test, verbose=0)
model.predict(X_test, verbose=0)
model.predict_classes(X_test, verbose=0)
model.predict_proba(X_test, verbose=0)
fname = 'test_merge_overlap_temp.h5'
print(model.layers)
model.save_weights(fname, overwrite=True)
print(model.trainable_weights)
model.load_weights(fname)
os.remove(fname)
nloss = model.evaluate(X_test, y_test, verbose=0)
assert(loss == nloss)
# test serialization
config = model.get_config()
new_model = Sequential.from_config(config)
model.summary()
json_str = model.to_json()
new_model = model_from_json(json_str)
yaml_str = model.to_yaml()
new_model = model_from_yaml(yaml_str)
示例14: __init__
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def __init__(self, env,
nn = None,
**config):
"""
Based on:
https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf
Parameters
"""
# if not isinstance(env.action_space, discrete.Discrete):
# raise UnsupportedSpace('Action space {} incompatible with {}. (Only supports Discrete action spaces.)'.format(action_space, self))
self.env = env
self.config = {
'eps': 0.05,
'gamma': 0.95,
'store_every':5,
'train_every':5,
'minibatch_size': 1,
'max_experience': 5000,
'target_nn_update_rate': 0.01,
'maxepoch': 100,
'maxstep': 100,
'outdir': '/tmp/brainresults',
'plot': True,
'render': True,
}
self.config.update(config)
self.plotter = LivePlot(self.config['outdir'])
# Deep Q Agent State
self._action_ctr = 0 # actions excuted so far
self._iter_ctr = 0
self._store_ctr = 0
self._train_ctr = 0
self._experience = deque()
self.nn = nn # The keras network should be compiled outside
self.tnn = Sequential.from_config(nn.get_config()) # Init target NN
self.tnn.set_weights(self.nn.get_weights())
示例15: load_keras_model_from_disk
# 需要导入模块: from keras.models import Sequential [as 别名]
# 或者: from keras.models.Sequential import from_config [as 别名]
def load_keras_model_from_disk(
model_json_path,
weights_hdf_path,
name=None):
"""
Loads a model from two files on disk: a JSON configuration and HDF5 weights.
Parameters
----------
model_json_path : str
weights_hdf_path : str
name : str, optional
Returns a Keras model.
"""
if not exists(model_json_path):
raise ValueError("Model file %s (name = %s) not found" % (
model_json_path, name,))
with open(model_json_path, "r") as f:
config_dict = json.load(f)
if isinstance(config_dict, list):
# not sure if this is a Keras bug but depending on the model I get back
# either a list or a dict, the list is only usable with a Sequential
# model
model = Sequential.from_config(config_dict)
else:
model = model_from_config(config_dict)
if weights_hdf_path is not None:
if not exists(weights_hdf_path):
raise ValueError(
"Missing model weights file %s (name = %s)" % (weights_hdf_path, name))
model.load_weights(weights_hdf_path)
return model