本文整理汇总了Python中tensorflow.keras.models.Sequential方法的典型用法代码示例。如果您正苦于以下问题:Python models.Sequential方法的具体用法?Python models.Sequential怎么用?Python models.Sequential使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.keras.models
的用法示例。
在下文中一共展示了models.Sequential方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def build(self, input_shape):
assert len(input_shape) >= 2
layer_kwargs = dict(
kernel_initializer=self.kernel_initializer,
bias_initializer=self.bias_initializer,
kernel_regularizer=self.kernel_regularizer,
bias_regularizer=self.bias_regularizer,
kernel_constraint=self.kernel_constraint,
bias_constraint=self.bias_constraint
)
self.mlp = Sequential([
Dense(channels, self.mlp_activation, **layer_kwargs)
for channels in self.mlp_hidden
] + [Dense(self.channels, self.activation, use_bias=self.use_bias, **layer_kwargs)])
self.built = True
示例2: build
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def build(self, input_shape):
assert len(input_shape) >= 2
layer_kwargs = dict(
kernel_initializer=self.kernel_initializer,
bias_initializer=self.bias_initializer,
kernel_regularizer=self.kernel_regularizer,
bias_regularizer=self.bias_regularizer,
kernel_constraint=self.kernel_constraint,
bias_constraint=self.bias_constraint
)
mlp_layers = []
for i, channels in enumerate(self.mlp_hidden):
mlp_layers.extend([
Dropout(self.dropout_rate),
Dense(channels, self.mlp_activation, **layer_kwargs)
])
mlp_layers.append(
Dense(self.channels, 'linear', **layer_kwargs)
)
self.mlp = Sequential(mlp_layers)
self.built = True
示例3: build
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def build(self, input_shape):
assert len(input_shape) >= 2
layer_kwargs = dict(
kernel_initializer=self.kernel_initializer,
bias_initializer=self.bias_initializer,
kernel_regularizer=self.kernel_regularizer,
bias_regularizer=self.bias_regularizer,
kernel_constraint=self.kernel_constraint,
bias_constraint=self.bias_constraint
)
self.mlp = Sequential([
Dense(channels, self.mlp_activation, **layer_kwargs)
for channels in self.mlp_hidden
] + [Dense(self.channels, self.activation, use_bias=self.use_bias, **layer_kwargs)])
if self.epsilon is None:
self.eps = self.add_weight(shape=(1,),
initializer='zeros',
name='eps')
else:
# If epsilon is given, keep it constant
self.eps = K.constant(self.epsilon)
self.built = True
示例4: test_single_ddpg_input
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def test_single_ddpg_input():
nb_actions = 2
actor = Sequential()
actor.add(Flatten(input_shape=(2, 3)))
actor.add(Dense(nb_actions))
action_input = Input(shape=(nb_actions,), name='action_input')
observation_input = Input(shape=(2, 3), name='observation_input')
x = Concatenate()([action_input, Flatten()(observation_input)])
x = Dense(1)(x)
critic = Model(inputs=[action_input, observation_input], outputs=x)
memory = SequentialMemory(limit=10, window_length=2)
agent = DDPGAgent(actor=actor, critic=critic, critic_action_input=action_input, memory=memory,
nb_actions=2, nb_steps_warmup_critic=5, nb_steps_warmup_actor=5, batch_size=4)
agent.compile('sgd')
agent.fit(MultiInputTestEnv((3,)), nb_steps=10)
示例5: test_dqn
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def test_dqn():
env = TwoRoundDeterministicRewardEnv()
np.random.seed(123)
env.seed(123)
random.seed(123)
nb_actions = env.action_space.n
# Next, we build a very simple model.
model = Sequential()
model.add(Dense(16, input_shape=(1,)))
model.add(Activation('relu'))
model.add(Dense(nb_actions))
model.add(Activation('linear'))
memory = SequentialMemory(limit=1000, window_length=1)
policy = EpsGreedyQPolicy(eps=.1)
dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=50,
target_model_update=1e-1, policy=policy, enable_double_dqn=False)
dqn.compile(Adam(lr=1e-3))
dqn.fit(env, nb_steps=2000, visualize=False, verbose=0)
policy.eps = 0.
h = dqn.test(env, nb_episodes=20, visualize=False)
assert_allclose(np.mean(h.history['episode_reward']), 3.)
示例6: test_double_dqn
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def test_double_dqn():
env = TwoRoundDeterministicRewardEnv()
np.random.seed(123)
env.seed(123)
random.seed(123)
nb_actions = env.action_space.n
# Next, we build a very simple model.
model = Sequential()
model.add(Dense(16, input_shape=(1,)))
model.add(Activation('relu'))
model.add(Dense(nb_actions))
model.add(Activation('linear'))
memory = SequentialMemory(limit=1000, window_length=1)
policy = EpsGreedyQPolicy(eps=.1)
dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=50,
target_model_update=1e-1, policy=policy, enable_double_dqn=True)
dqn.compile(Adam(lr=1e-3))
dqn.fit(env, nb_steps=2000, visualize=False, verbose=0)
policy.eps = 0.
h = dqn.test(env, nb_episodes=20, visualize=False)
assert_allclose(np.mean(h.history['episode_reward']), 3.)
示例7: test_cem
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def test_cem():
env = TwoRoundDeterministicRewardEnv()
np.random.seed(123)
env.seed(123)
random.seed(123)
nb_actions = env.action_space.n
# Next, we build a very simple model.
model = Sequential()
model.add(Dense(16, input_shape=(1,)))
model.add(Activation('relu'))
model.add(Dense(nb_actions))
model.add(Activation('linear'))
memory = EpisodeParameterMemory(limit=1000, window_length=1)
dqn = CEMAgent(model=model, nb_actions=nb_actions, memory=memory)
dqn.compile()
dqn.fit(env, nb_steps=2000, visualize=False, verbose=1)
h = dqn.test(env, nb_episodes=20, visualize=False)
assert_allclose(np.mean(h.history['episode_reward']), 3.)
示例8: test_sarsa
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def test_sarsa():
env = TwoRoundDeterministicRewardEnv()
np.random.seed(123)
env.seed(123)
random.seed(123)
nb_actions = env.action_space.n
# Next, we build a very simple model.
model = Sequential()
model.add(Dense(16, input_shape=(1,)))
model.add(Activation('relu'))
model.add(Dense(nb_actions, activation='linear'))
policy = EpsGreedyQPolicy(eps=.1)
sarsa = SARSAAgent(model=model, nb_actions=nb_actions, nb_steps_warmup=50, policy=policy)
sarsa.compile(Adam(lr=1e-3))
sarsa.fit(env, nb_steps=20000, visualize=False, verbose=0)
policy.eps = 0.
h = sarsa.test(env, nb_episodes=20, visualize=False)
assert_allclose(np.mean(h.history['episode_reward']), 3.)
示例9: construct_q_network
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def construct_q_network(self):
# replacement of the Convolution layers by Dense layers, and change the size of the input space and output space
# Uses the network architecture found in DeepMind paper
self.model = Sequential()
input_layer = Input(shape=(self.observation_size * self.training_param.NUM_FRAMES,))
layer1 = Dense(self.observation_size * self.training_param.NUM_FRAMES)(input_layer)
layer1 = Activation('relu')(layer1)
layer2 = Dense(self.observation_size)(layer1)
layer2 = Activation('relu')(layer2)
layer3 = Dense(self.observation_size)(layer2)
layer3 = Activation('relu')(layer3)
layer4 = Dense(2 * self.action_size)(layer3)
layer4 = Activation('relu')(layer4)
output = Dense(self.action_size)(layer4)
self.model = Model(inputs=[input_layer], outputs=[output])
self.model.compile(loss='mse', optimizer=Adam(lr=self.lr_))
self.target_model = Model(inputs=[input_layer], outputs=[output])
self.target_model.compile(loss='mse', optimizer=Adam(lr=self.lr_))
self.target_model.set_weights(self.model.get_weights())
示例10: __init__
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def __init__(self,
featurizer: Optional[TrackerFeaturizer] = None,
priority: int = 1,
model: Optional[tf.keras.models.Sequential] = None,
graph: Optional[tf.Graph] = None,
session: Optional[tf.Session] = None,
current_epoch: int = 0,
max_history: Optional[int] = None,
**kwargs: Any
) -> None:
if not featurizer:
featurizer = self._standard_featurizer(max_history)
super(KerasPolicy, self).__init__(featurizer, priority)
self._load_params(**kwargs)
self.model = model
# by default keras uses default tf graph and global tf session
# we are going to either load them or create them in train(...)
self.graph = graph
self.session = session
self.current_epoch = current_epoch
示例11: _keras_conv2d_core
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def _keras_conv2d_core(shape=None, data=None):
assert shape is None or data is None
if shape is None:
shape = data.shape
init = tf.keras.initializers.RandomNormal(seed=1)
model = Sequential()
c2d = Conv2D(
2,
(3, 3),
data_format="channels_last",
use_bias=False,
kernel_initializer=init,
input_shape=shape[1:],
)
model.add(c2d)
if data is None:
data = np.random.uniform(size=shape)
out = model.predict(data)
return model, out
示例12: _keras_depthwise_conv2d_core
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def _keras_depthwise_conv2d_core(shape=None, data=None):
assert shape is None or data is None
if shape is None:
shape = data.shape
init = tf.keras.initializers.RandomNormal(seed=1)
model = Sequential()
c2d = DepthwiseConv2D(
(3, 3),
depthwise_initializer=init,
data_format="channels_last",
use_bias=False,
input_shape=shape[1:],
)
model.add(c2d)
if data is None:
data = np.random.uniform(size=shape)
out = model.predict(data)
return model, out
示例13: test_triplet_network
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def test_triplet_network():
X = np.zeros(shape=(10, 5))
embedding_dims = 3
base_model = Sequential()
base_model.add(Dense(8, input_shape=(X.shape[-1],)))
model, _, _, _ = triplet_network(base_model, embedding_dims=embedding_dims, embedding_l2=0.1)
encoder = model.layers[3]
assert model.layers[3].output_shape == (None, 3)
assert np.all(base_model.get_weights()[0] == encoder.get_weights()[0])
assert np.all([isinstance(layer, keras.layers.InputLayer) for layer in model.layers[:3]])
assert encoder.output_shape == (None, embedding_dims)
示例14: get_model
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def get_model(args):
model = models.Sequential()
model.add(
layers.Conv2D(args.conv1_size, (3, 3), activation=args.conv_activation, input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(args.conv2_size, (3, 3), activation=args.conv_activation))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation=args.conv_activation))
model.add(layers.Dropout(args.dropout))
model.add(layers.Flatten())
model.add(layers.Dense(args.hidden1_size, activation=args.dense_activation))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
model.compile(optimizer=OPTIMIZERS[args.optimizer](learning_rate=args.learning_rate),
loss=args.loss,
metrics=['accuracy'])
return model
示例15: make_model
# 需要导入模块: from tensorflow.keras import models [as 别名]
# 或者: from tensorflow.keras.models import Sequential [as 别名]
def make_model(dummy_data):
# pylint: disable=redefined-outer-name
data, _ = dummy_data
model = Sequential()
model.add(
Conv2DMPO(filters=4,
kernel_size=3,
num_nodes=2,
bond_dim=10,
padding='same',
input_shape=data.shape[1:],
name=LAYER_NAME)
)
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
return model