本文整理汇总了Python中tensorflow.keras.layers.Flatten方法的典型用法代码示例。如果您正苦于以下问题:Python layers.Flatten方法的具体用法?Python layers.Flatten怎么用?Python layers.Flatten使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.keras.layers
的用法示例。
在下文中一共展示了layers.Flatten方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _create_encoder
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def _create_encoder(self, n_layers, dropout):
"""Create the encoder as a tf.keras.Model."""
input = self._create_features()
gather_indices = Input(shape=(2,), dtype=tf.int32)
prev_layer = input
for i in range(len(self._filter_sizes)):
filter_size = self._filter_sizes[i]
kernel_size = self._kernel_sizes[i]
if dropout > 0.0:
prev_layer = Dropout(rate=dropout)(prev_layer)
prev_layer = Conv1D(
filters=filter_size, kernel_size=kernel_size,
activation=tf.nn.relu)(prev_layer)
prev_layer = Flatten()(prev_layer)
prev_layer = Dense(
self._decoder_dimension, activation=tf.nn.relu)(prev_layer)
prev_layer = BatchNormalization()(prev_layer)
return tf.keras.Model(inputs=[input, gather_indices], outputs=prev_layer)
示例2: __init__
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def __init__(self, filters, size=3, apply_batchnorm=True):
super(SFL, self).__init__()
self.apply_batchnorm = apply_batchnorm
# depth map
self.cru1 = CRU(filters, size, stride=1)
self.conv1 = Conv(2, size, activation=False, apply_batchnorm=False)
# class
self.conv2 = Downsample(filters*1, size)
self.conv3 = Downsample(filters*1, size)
self.conv4 = Downsample(filters*2, size)
self.conv5 = Downsample(filters*4, 4, padding='VALID')
self.flatten = layers.Flatten()
self.fc1 = Dense(256)
self.fc2 = Dense(1, activation=False, apply_batchnorm=False)
self.dropout = tf.keras.layers.Dropout(0.3)
示例3: __init__
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def __init__(self, state_shape, action_dim, units=None,
name="AtariCategoricalActorCritic"):
tf.keras.Model.__init__(self, name=name)
self.dist = Categorical(dim=action_dim)
self.action_dim = action_dim
self.conv1 = Conv2D(32, kernel_size=(8, 8), strides=(4, 4),
padding='valid', activation='relu')
self.conv2 = Conv2D(64, kernel_size=(4, 4), strides=(2, 2),
padding='valid', activation='relu')
self.conv3 = Conv2D(64, kernel_size=(3, 3), strides=(1, 1),
padding='valid', activation='relu')
self.flat = Flatten()
self.fc1 = Dense(512, activation='relu')
self.prob = Dense(action_dim, activation='softmax')
self.v = Dense(1, activation="linear")
self(tf.constant(
np.zeros(shape=(1,)+state_shape, dtype=np.float32)))
示例4: test_single_ddpg_input
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [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_single_continuous_dqn_input
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def test_single_continuous_dqn_input():
nb_actions = 2
V_model = Sequential()
V_model.add(Flatten(input_shape=(2, 3)))
V_model.add(Dense(1))
mu_model = Sequential()
mu_model.add(Flatten(input_shape=(2, 3)))
mu_model.add(Dense(nb_actions))
L_input = Input(shape=(2, 3))
L_input_action = Input(shape=(nb_actions,))
x = Concatenate()([Flatten()(L_input), L_input_action])
x = Dense(((nb_actions * nb_actions + nb_actions) // 2))(x)
L_model = Model(inputs=[L_input_action, L_input], outputs=x)
memory = SequentialMemory(limit=10, window_length=2)
agent = NAFAgent(nb_actions=nb_actions, V_model=V_model, L_model=L_model, mu_model=mu_model,
memory=memory, nb_steps_warmup=5, batch_size=4)
agent.compile('sgd')
agent.fit(MultiInputTestEnv((3,)), nb_steps=10)
示例6: process_hidden_layers
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def process_hidden_layers(self, x, training):
"""Puts the data x through all the hidden layers"""
flattened=False
training = training or training is None
valid_batch_norm_layer_ix = 0
for layer_ix, layer in enumerate(self.hidden_layers):
if type(layer) in self.valid_layer_types_with_no_parameters:
x = layer(x)
else:
if type(layer) == Dense and not flattened:
x = Flatten()(x)
flattened = True
x = layer(x)
if self.batch_norm:
x = self.batch_norm_layers[valid_batch_norm_layer_ix](x, training=False)
valid_batch_norm_layer_ix += 1
if self.dropout != 0.0 and training: x = self.dropout_layer(x)
if not flattened: x = Flatten()(x)
return x
示例7: build_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def build_model(self):
"""Build the n_heads of the IIC model
"""
inputs = Input(shape=self.train_gen.input_shape, name='x')
x = self.backbone(inputs)
x = Flatten()(x)
# number of output heads
outputs = []
for i in range(self.args.heads):
name = "z_head%d" % i
outputs.append(Dense(self.n_labels,
activation='softmax',
name=name)(x))
self._model = Model(inputs, outputs, name='encoder')
optimizer = Adam(lr=1e-3)
self._model.compile(optimizer=optimizer, loss=self.mi_loss)
self._model.summary()
示例8: ConvLayer
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def ConvLayer(conv_function=Conv2D,
filters=[32, 64, 64],
kernels=[[8, 8], [4, 4], [3, 3]],
strides=[[4, 4], [2, 2], [1, 1]],
padding='valid',
activation='relu'):
'''
Params:
conv_function: the convolution function
filters: list of flitter of all hidden conv layers
kernels: list of kernel of all hidden conv layers
strides: list of stride of all hidden conv layers
padding: padding mode
activation: activation function
Return:
A sequential of multi-convolution layers, with Flatten.
'''
layers = Sequential([conv_function(filters=f, kernel_size=k, strides=s, padding=padding, activation=activation) for f, k, s in zip(filters, kernels, strides)])
layers.add(Flatten())
return layers
示例9: get_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [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
示例10: make_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [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
示例11: call
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def call(self, inputs): # (B, S, H)
# Expand weights to include batch size through implicit broadcasting
W1, W2 = self.W1[None, :, :], self.W2[None, :, :]
hidden_states_transposed = Permute(dims=(2, 1))(inputs) # (B, H, S)
attention_score = tf.matmul(W1, hidden_states_transposed) # (B, size, S)
attention_score = Activation('tanh')(attention_score) # (B, size, S)
attention_weights = tf.matmul(W2, attention_score) # (B, num_hops, S)
attention_weights = Activation('softmax')(attention_weights) # (B, num_hops, S)
embedding_matrix = tf.matmul(attention_weights, inputs) # (B, num_hops, H)
embedding_matrix_flattened = Flatten()(embedding_matrix) # (B, num_hops*H)
if self.use_penalization:
attention_weights_transposed = Permute(dims=(2, 1))(attention_weights) # (B, S, num_hops)
product = tf.matmul(attention_weights, attention_weights_transposed) # (B, num_hops, num_hops)
identity = tf.eye(self.num_hops, batch_shape=(inputs.shape[0],)) # (B, num_hops, num_hops)
frobenius_norm = tf.sqrt(tf.reduce_sum(tf.square(product - identity))) # distance
self.add_loss(self.penalty_coefficient * frobenius_norm) # loss
if self.model_api == 'functional':
return embedding_matrix_flattened, attention_weights
elif self.model_api == 'sequential':
return embedding_matrix_flattened
示例12: build_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def build_model(hp):
model = keras.Sequential()
model.add(layers.Flatten(input_shape=(28, 28)))
min_layers = 2
max_layers = 5
for i in range(hp.Int('num_layers', min_layers, max_layers)):
model.add(layers.Dense(units=hp.Int('units_' + str(i),
32,
256,
32,
parent_name='num_layers',
parent_values=list(range(i + 1, max_layers + 1))),
activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.compile(
optimizer=keras.optimizers.Adam(1e-4),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
示例13: build
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def build(self, hp, inputs=None):
inputs = nest.flatten(inputs)
if len(inputs) == 1:
return inputs
merge_type = self.merge_type or hp.Choice('merge_type',
['add', 'concatenate'],
default='add')
if not all([shape_compatible(input_node.shape, inputs[0].shape) for
input_node in inputs]):
new_inputs = []
for input_node in inputs:
new_inputs.append(Flatten().build(hp, input_node))
inputs = new_inputs
# TODO: Even inputs have different shape[-1], they can still be Add(
# ) after another layer. Check if the inputs are all of the same
# shape
if all([input_node.shape == inputs[0].shape for input_node in inputs]):
if merge_type == 'add':
return layers.Add(inputs)
return layers.Concatenate()(inputs)
示例14: keras_estimator
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def keras_estimator(model_dir, config, learning_rate):
"""Creates a Keras Sequential model with layers.
Args:
model_dir: (str) file path where training files will be written.
config: (tf.estimator.RunConfig) Configuration options to save model.
learning_rate: (int) Learning rate.
Returns:
A keras.Model
"""
model = models.Sequential()
model.add(Flatten(input_shape=(28, 28)))
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dense(10, activation=tf.nn.softmax))
# Compile model with learning parameters.
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
model.compile(
optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
estimator = tf.keras.estimator.model_to_estimator(
keras_model=model, model_dir=model_dir, config=config)
return estimator
示例15: test_single_cem_input
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Flatten [as 别名]
def test_single_cem_input():
model = Sequential()
model.add(Flatten(input_shape=(2, 3)))
model.add(Dense(2))
memory = EpisodeParameterMemory(limit=10, window_length=2)
agent = CEMAgent(model, memory=memory, nb_actions=2, nb_steps_warmup=5, batch_size=4, train_interval=50)
agent.compile()
agent.fit(MultiInputTestEnv((3,)), nb_steps=100)