本文整理汇总了Python中tensorflow.keras.layers.Reshape方法的典型用法代码示例。如果您正苦于以下问题:Python layers.Reshape方法的具体用法?Python layers.Reshape怎么用?Python layers.Reshape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.keras.layers
的用法示例。
在下文中一共展示了layers.Reshape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def create_model(trainable=False):
model = MobileNetV2(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), include_top=False, alpha=ALPHA)
# to freeze layers
for layer in model.layers:
layer.trainable = trainable
out = model.layers[-1].output
x = Conv2D(4, kernel_size=3)(out)
x = Reshape((4,), name="coords")(x)
y = GlobalAveragePooling2D()(out)
y = Dense(CLASSES, name="classes", activation="softmax")(y)
return Model(inputs=model.input, outputs=[x, y])
示例2: expand_tile
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def expand_tile(units, axis):
"""
Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
"""
assert axis in (1, 2)
n_time_steps = K.int_shape(units)[1]
repetitions = [1, 1, 1, 1]
repetitions[axis] = n_time_steps
if axis == 1:
expanded = Reshape(target_shape=((1,) + K.int_shape(units)[1:]))(units)
else:
expanded = Reshape(target_shape=(K.int_shape(units)[1:2] + (1,) + K.int_shape(units)[2:]))(units)
return K.tile(expanded, repetitions)
示例3: get_aggregation_gate
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def get_aggregation_gate(in_filters, reduction=16):
"""Get the "aggregation gate (AG)" op.
# Arguments
reduction: channel reduction for the hidden layer.
# Returns
The AG op (a models.Sequential module).
"""
gate = models.Sequential()
gate.add(layers.GlobalAveragePooling2D())
gate.add(layers.Dense(in_filters // reduction, use_bias=False))
gate.add(layers.BatchNormalization())
gate.add(layers.Activation('relu'))
gate.add(layers.Dense(in_filters))
gate.add(layers.Activation('sigmoid'))
gate.add(layers.Reshape((1, 1, -1))) # reshape as (H, W, C)
return gate
示例4: create_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def create_model(self):
print('[ImgDecoder] Starting create_model')
dense = Dense(units=1024, name='p_img_dense')
reshape = Reshape((1, 1, 1024))
# for 64x64 img
deconv1 = Conv2DTranspose(filters=128, kernel_size=4, strides=1, padding='valid', activation='relu')
deconv2 = Conv2DTranspose(filters=64, kernel_size=5, strides=1, padding='valid', activation='relu', dilation_rate=3)
deconv3 = Conv2DTranspose(filters=64, kernel_size=6, strides=1, padding='valid', activation='relu', dilation_rate=2)
deconv4 = Conv2DTranspose(filters=32, kernel_size=5, strides=2, padding='valid', activation='relu', dilation_rate=1)
deconv5 = Conv2DTranspose(filters=16, kernel_size=5, strides=1, padding='valid', activation='relu', dilation_rate=1)
# deconv6 = Conv2DTranspose(filters=8, kernel_size=6, strides=2, padding='valid', activation='relu')
deconv7 = Conv2DTranspose(filters=3, kernel_size=6, strides=1, padding='valid', activation='tanh')
self.network = tf.keras.Sequential([
dense,
reshape,
deconv1,
deconv2,
deconv3,
deconv4,
deconv5,
deconv7],
name='p_img')
print('[ImgDecoder] Done with create_model')
示例5: _se_block
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def _se_block(inputs, filters, se_ratio, prefix):
x = GlobalAveragePooling2D(name=prefix + 'squeeze_excite/AvgPool')(inputs)
if K.image_data_format() == 'channels_first':
x = Reshape((filters, 1, 1))(x)
else:
x = Reshape((1, 1, filters))(x)
x = Conv2D(_depth(filters * se_ratio),
kernel_size=1,
padding='same',
name=prefix + 'squeeze_excite/Conv')(x)
x = ReLU(name=prefix + 'squeeze_excite/Relu')(x)
x = Conv2D(filters,
kernel_size=1,
padding='same',
name=prefix + 'squeeze_excite/Conv_1')(x)
x = Activation(hard_sigmoid)(x)
#if K.backend() == 'theano':
## For the Theano backend, we have to explicitly make
## the excitation weights broadcastable.
#x = Lambda(
#lambda br: K.pattern_broadcast(br, [True, True, True, False]),
#output_shape=lambda input_shape: input_shape,
#name=prefix + 'squeeze_excite/broadcast')(x)
x = Multiply(name=prefix + 'squeeze_excite/Mul')([inputs, x])
return x
示例6: test_compute_model_performance_multitask_classifier
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def test_compute_model_performance_multitask_classifier(self):
n_data_points = 20
n_features = 1
n_tasks = 2
n_classes = 2
X = np.ones(shape=(n_data_points // 2, n_features)) * -1
X1 = np.ones(shape=(n_data_points // 2, n_features))
X = np.concatenate((X, X1))
class_1 = np.array([[0.0, 1.0] for x in range(int(n_data_points / 2))])
class_0 = np.array([[1.0, 0.0] for x in range(int(n_data_points / 2))])
y1 = np.concatenate((class_0, class_1))
y2 = np.concatenate((class_1, class_0))
y = np.stack([y1, y2], axis=1)
dataset = NumpyDataset(X, y)
features = layers.Input(shape=(n_data_points // 2, n_features))
dense = layers.Dense(n_tasks * n_classes)(features)
logits = layers.Reshape((n_tasks, n_classes))(dense)
output = layers.Softmax()(logits)
keras_model = tf.keras.Model(inputs=features, outputs=[output, logits])
model = dc.models.KerasModel(
keras_model,
dc.models.losses.SoftmaxCrossEntropy(),
output_types=['prediction', 'loss'],
learning_rate=0.01,
batch_size=n_data_points)
model.fit(dataset, nb_epoch=1000)
metric = dc.metrics.Metric(
dc.metrics.roc_auc_score, np.mean, mode="classification")
scores = model.evaluate_generator(
model.default_generator(dataset), [metric], per_task_metrics=True)
scores = list(scores[1].values())
# Loosening atol to see if tests stop failing sporadically
assert np.all(np.isclose(scores, [1.0, 1.0], atol=0.50))
示例7: _build_graph
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def _build_graph(self):
smile_images = Input(shape=self.input_shape)
stem = chemnet_layers.Stem(self.base_filters)(smile_images)
inceptionA_out = self.build_inception_module(inputs=stem, type="A")
reductionA_out = chemnet_layers.ReductionA(
self.base_filters)(inceptionA_out)
inceptionB_out = self.build_inception_module(
inputs=reductionA_out, type="B")
reductionB_out = chemnet_layers.ReductionB(
self.base_filters)(inceptionB_out)
inceptionC_out = self.build_inception_module(
inputs=reductionB_out, type="C")
avg_pooling_out = GlobalAveragePooling2D()(inceptionC_out)
if self.mode == "classification":
logits = Dense(self.n_tasks * self.n_classes)(avg_pooling_out)
logits = Reshape((self.n_tasks, self.n_classes))(logits)
if self.n_classes == 2:
output = Activation(activation='sigmoid')(logits)
loss = SigmoidCrossEntropy()
else:
output = Softmax()(logits)
loss = SoftmaxCrossEntropy()
outputs = [output, logits]
output_types = ['prediction', 'loss']
else:
output = Dense(self.n_tasks * 1)(avg_pooling_out)
output = Reshape((self.n_tasks, 1))(output)
outputs = [output]
output_types = ['prediction']
loss = L2Loss()
model = tf.keras.Model(inputs=[smile_images], outputs=outputs)
return model, loss, output_types
示例8: squeeze_excite_block
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def squeeze_excite_block(input_tensor, ratio=16):
""" Create a channel-wise squeeze-excite block
Args:
input_tensor: input Keras tensor
ratio: number of output filters
Returns: a Keras tensor
References
- [Squeeze and Excitation Networks](https://arxiv.org/abs/1709.01507)
"""
init = input_tensor
channel_axis = 1 if K.image_data_format() == "channels_first" else -1
filters = _tensor_shape(init)[channel_axis]
se_shape = (1, 1, filters)
se = GlobalAveragePooling2D()(init)
se = Reshape(se_shape)(se)
se = Dense(filters // ratio, activation='relu', kernel_initializer='he_normal', use_bias=False)(se)
se = Dense(filters, activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(se)
if K.image_data_format() == 'channels_first':
se = Permute((3, 1, 2))(se)
x = multiply([init, se])
return x
示例9: create_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def create_model(trainable=False):
model = MobileNetV2(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), include_top=False, alpha=ALPHA)
# to freeze layers
for layer in model.layers:
layer.trainable = trainable
x = model.layers[-1].output
x = Conv2D(4, kernel_size=3, name="coords")(x)
x = Reshape((4,))(x)
return Model(inputs=model.input, outputs=x)
示例10: CAE
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def CAE(input_shape=(28, 28, 1), filters=[32, 64, 128, 10]):
model = Sequential()
if input_shape[0] % 8 == 0:
pad3 = 'same'
else:
pad3 = 'valid'
model.add(InputLayer(input_shape))
model.add(Conv2D(filters[0], 5, strides=2, padding='same', activation='relu', name='conv1'))
model.add(Conv2D(filters[1], 5, strides=2, padding='same', activation='relu', name='conv2'))
model.add(Conv2D(filters[2], 3, strides=2, padding=pad3, activation='relu', name='conv3'))
model.add(Flatten())
model.add(Dense(units=filters[3], name='embedding'))
model.add(Dense(units=filters[2]*int(input_shape[0]/8)*int(input_shape[0]/8), activation='relu'))
model.add(Reshape((int(input_shape[0]/8), int(input_shape[0]/8), filters[2])))
model.add(Conv2DTranspose(filters[1], 3, strides=2, padding=pad3, activation='relu', name='deconv3'))
model.add(Conv2DTranspose(filters[0], 5, strides=2, padding='same', activation='relu', name='deconv2'))
model.add(Conv2DTranspose(input_shape[2], 5, strides=2, padding='same', name='deconv1'))
encoder = Model(inputs=model.input, outputs=model.get_layer('embedding').output)
return model, encoder
示例11: __init__
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def __init__(self, batch_input_shape=(None, NUM_FRAMES, NUM_FBANKS, 1), include_softmax=False,
num_speakers_softmax=None):
self.include_softmax = include_softmax
if self.include_softmax:
assert num_speakers_softmax > 0
self.clipped_relu_count = 0
# http://cs231n.github.io/convolutional-networks/
# conv weights
# #params = ks * ks * nb_filters * num_channels_input
# Conv128-s
# 5*5*128*128/2+128
# ks*ks*nb_filters*channels/strides+bias(=nb_filters)
# take 100 ms -> 4 frames.
# if signal is 3 seconds, then take 100ms per 100ms and average out this network.
# 8*8 = 64 features.
# used to share all the layers across the inputs
# num_frames = K.shape() - do it dynamically after.
inputs = Input(batch_shape=batch_input_shape, name='input')
x = self.cnn_component(inputs)
x = Reshape((-1, 2048))(x)
# Temporal average layer. axis=1 is time.
x = Lambda(lambda y: K.mean(y, axis=1), name='average')(x)
if include_softmax:
logger.info('Including a Dropout layer to reduce overfitting.')
# used for softmax because the dataset we pre-train on might be too small. easy to overfit.
x = Dropout(0.5)(x)
x = Dense(512, name='affine')(x)
if include_softmax:
# Those weights are just when we train on softmax.
x = Dense(num_speakers_softmax, activation='softmax')(x)
else:
# Does not contain any weights.
x = Lambda(lambda y: K.l2_normalize(y, axis=1), name='ln')(x)
self.m = Model(inputs, x, name='ResCNN')
示例12: build_model
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def build_model(board_size=4, board_layers=16, outputs=4, filters=64, residual_blocks=4):
# Functional API model
inputs = layers.Input(shape=(board_size * board_size * board_layers,))
x = layers.Reshape((board_size, board_size, board_layers))(inputs)
# Initial convolutional block
x = layers.Conv2D(filters=filters, kernel_size=(3, 3), padding='same')(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
# residual blocks
for i in range(residual_blocks):
# x at the start of a block
temp_x = layers.Conv2D(filters=filters, kernel_size=(3, 3), padding='same')(x)
temp_x = layers.BatchNormalization()(temp_x)
temp_x = layers.Activation('relu')(temp_x)
temp_x = layers.Conv2D(filters=filters, kernel_size=(3, 3), padding='same')(temp_x)
temp_x = layers.BatchNormalization()(temp_x)
x = layers.add([x, temp_x])
x = layers.Activation('relu')(x)
# policy head
x = layers.Conv2D(filters=2, kernel_size=(1, 1), padding='same')(x)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.Flatten()(x)
predictions = layers.Dense(outputs, activation='softmax')(x)
# Create model
return models.Model(inputs=inputs, outputs=predictions)
示例13: __init__
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def __init__(self, width, depth, num_anchors=9, separable_conv=True, freeze_bn=False, detect_quadrangle=False, **kwargs):
super(BoxNet, self).__init__(**kwargs)
self.width = width
self.depth = depth
self.num_anchors = num_anchors
self.separable_conv = separable_conv
self.detect_quadrangle = detect_quadrangle
num_values = 9 if detect_quadrangle else 4
options = {
'kernel_size': 3,
'strides': 1,
'padding': 'same',
'bias_initializer': 'zeros',
}
if separable_conv:
kernel_initializer = {
'depthwise_initializer': initializers.VarianceScaling(),
'pointwise_initializer': initializers.VarianceScaling(),
}
options.update(kernel_initializer)
self.convs = [layers.SeparableConv2D(filters=width, name=f'{self.name}/box-{i}', **options) for i in
range(depth)]
self.head = layers.SeparableConv2D(filters=num_anchors * num_values,
name=f'{self.name}/box-predict', **options)
else:
kernel_initializer = {
'kernel_initializer': initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None)
}
options.update(kernel_initializer)
self.convs = [layers.Conv2D(filters=width, name=f'{self.name}/box-{i}', **options) for i in range(depth)]
self.head = layers.Conv2D(filters=num_anchors * num_values, name=f'{self.name}/box-predict', **options)
self.bns = [
[layers.BatchNormalization(momentum=MOMENTUM, epsilon=EPSILON, name=f'{self.name}/box-{i}-bn-{j}') for j in
range(3, 8)]
for i in range(depth)]
# self.bns = [[BatchNormalization(freeze=freeze_bn, name=f'{self.name}/box-{i}-bn-{j}') for j in range(3, 8)]
# for i in range(depth)]
self.relu = layers.Lambda(lambda x: tf.nn.swish(x))
self.reshape = layers.Reshape((-1, num_values))
self.level = 0
示例14: channel_squeeze_excite_block
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def channel_squeeze_excite_block(input, ratio=0.25):
init = input
channel_axis = 1 if K.image_data_format() == "channels_first" else -1
filters = init._keras_shape[channel_axis]
cse_shape = (1, 1, filters)
cse = layers.GlobalAveragePooling2D()(init)
cse = layers.Reshape(cse_shape)(cse)
ratio_filters = int(np.round(filters * ratio))
if ratio_filters < 1:
ratio_filters += 1
cse = layers.Conv2D(
ratio_filters,
(1, 1),
padding="same",
activation="relu",
kernel_initializer="he_normal",
use_bias=False,
)(cse)
cse = layers.BatchNormalization()(cse)
cse = layers.Conv2D(
filters,
(1, 1),
activation="sigmoid",
kernel_initializer="he_normal",
use_bias=False,
)(cse)
if K.image_data_format() == "channels_first":
cse = layers.Permute((3, 1, 2))(cse)
cse = layers.Multiply()([init, cse])
return cse
示例15: _fca_block
# 需要导入模块: from tensorflow.keras import layers [as 别名]
# 或者: from tensorflow.keras.layers import Reshape [as 别名]
def _fca_block(inputs, reduct_ratio, block_id):
in_channels = inputs.shape.as_list()[-1]
#in_shapes = inputs.shape.as_list()[1:3]
reduct_channels = int(in_channels // reduct_ratio)
prefix = 'fca_block_{}_'.format(block_id)
x = GlobalAveragePooling2D(name=prefix + 'average_pooling')(inputs)
x = Dense(reduct_channels, activation='relu', name=prefix + 'fc1')(x)
x = Dense(in_channels, activation='sigmoid', name=prefix + 'fc2')(x)
x = Reshape((1,1,in_channels),name='reshape')(x)
x = Multiply(name=prefix + 'multiply')([x, inputs])
return x