本文整理匯總了Python中tensorflow.keras.layers.Conv2D方法的典型用法代碼示例。如果您正苦於以下問題:Python layers.Conv2D方法的具體用法?Python layers.Conv2D怎麽用?Python layers.Conv2D使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tensorflow.keras.layers
的用法示例。
在下文中一共展示了layers.Conv2D方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def __init__(self, out_features,**kwargs):
super(_DenseLayer, self).__init__(**kwargs)
k_reg = None if w_decay is None else l2(w_decay)
self.layers = []
self.layers.append(tf.keras.Sequential(
[
layers.ReLU(),
layers.Conv2D(
filters=out_features, kernel_size=(3,3), strides=(1,1), padding='same',
use_bias=True, kernel_initializer=weight_init,
kernel_regularizer=k_reg),
layers.BatchNormalization(),
layers.ReLU(),
layers.Conv2D(
filters=out_features, kernel_size=(3,3), strides=(1,1), padding='same',
use_bias=True, kernel_initializer=weight_init,
kernel_regularizer=k_reg),
layers.BatchNormalization(),
])) # first relu can be not needed
示例2: conv2d_bn
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def conv2d_bn(x,
filters,
kernel_size,
strides=1,
padding='same',
activation='relu',
use_bias=False,
name=None):
x = Conv2D(filters,
kernel_size,
strides=strides,
padding=padding,
use_bias=use_bias,
name=name)(x)
if not use_bias:
bn_axis = 1 if K.image_data_format() == 'channels_first' else 3
bn_name = _generate_layer_name('BatchNorm', prefix=name)
x = BatchNormalization(axis=bn_axis, momentum=0.995, epsilon=0.001,
scale=False, name=bn_name)(x)
if activation is not None:
ac_name = _generate_layer_name('Activation', prefix=name)
x = Activation(activation, name=ac_name)(x)
return x
示例3: __init__
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [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: up_stage
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def up_stage(inputs, skip, filters, kernel_size=3,
activation="relu", padding="SAME"):
up = UpSampling2D()(inputs)
up = Conv2D(filters, 2, activation=activation, padding=padding)(up)
up = GroupNormalization()(up)
merge = concatenate([skip, up])
merge = GroupNormalization()(merge)
conv = Conv2D(filters, kernel_size,
activation=activation, padding=padding)(merge)
conv = GroupNormalization()(conv)
conv = Conv2D(filters, kernel_size,
activation=activation, padding=padding)(conv)
conv = GroupNormalization()(conv)
conv = SpatialDropout2D(0.5)(conv, training=True)
return conv
示例5: spatial_squeeze_excite_block
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def spatial_squeeze_excite_block(input_tensor):
""" Create a spatial squeeze-excite block
Args:
input_tensor: input Keras tensor
Returns: a Keras tensor
References
- [Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks](https://arxiv.org/abs/1803.02579)
"""
se = Conv2D(1, (1, 1), activation='sigmoid', use_bias=False,
kernel_initializer='he_normal')(input_tensor)
x = multiply([input_tensor, se])
return x
示例6: __init__
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def __init__(self,
data_format="channels_last",
**kwargs):
super(TF2Model, self).__init__(**kwargs)
padding = (3, 3)
if isinstance(padding, int):
padding = (padding, padding)
if is_channels_first(data_format):
self.paddings_tf = [[0, 0], [0, 0], list(padding), list(padding)]
else:
self.paddings_tf = [[0, 0], list(padding), list(padding), [0, 0]]
self.conv = nn.Conv2D(
filters=64,
kernel_size=(7, 7),
strides=2,
padding="valid",
data_format=data_format,
dilation_rate=1,
use_bias=False,
name="conv")
示例7: create_and_append_layer
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def create_and_append_layer(self, layer, list_to_append_layer_to, activation=None, output_layer=False):
"""Creates and appends a layer to the list provided"""
layer_name = layer[0].lower()
assert layer_name in self.valid_cnn_hidden_layer_types, "Layer name {} not valid, use one of {}".format(
layer_name, self.valid_cnn_hidden_layer_types)
if layer_name == "conv":
list_to_append_layer_to.extend([Conv2D(filters=layer[1], kernel_size=layer[2],
strides=layer[3], padding=layer[4], activation=activation,
kernel_initializer=self.initialiser_function)])
elif layer_name == "maxpool":
list_to_append_layer_to.extend([MaxPool2D(pool_size=(layer[1], layer[1]),
strides=(layer[2], layer[2]), padding=layer[3])])
elif layer_name == "avgpool":
list_to_append_layer_to.extend([AveragePooling2D(pool_size=(layer[1], layer[1]),
strides=(layer[2], layer[2]), padding=layer[3])])
elif layer_name == "linear":
list_to_append_layer_to.extend([Dense(layer[1], activation=activation, kernel_initializer=self.initialiser_function)])
else:
raise ValueError("Wrong layer name")
示例8: __init__
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def __init__(self,
input_name: str = 'encoder_output',
output_name: str = 'contact_prob'):
super().__init__()
self._input_name = input_name
self._output_name = output_name
def concat_pairs(tensor):
input_mul = tensor[:, :, None] * tensor[:, None, :]
input_sub = tf.abs(tensor[:, :, None] - tensor[:, None, :])
output = tf.concat((input_mul, input_sub), -1)
return output
self.get_pairwise_feature_vector = Lambda(concat_pairs)
self.predict_contact_map = Stack()
self.predict_contact_map.add(Conv2D(32, 1, use_bias=True, padding='same', activation='relu'))
self.predict_contact_map.add(Conv2D(1, 7, use_bias=True, padding='same', activation='linear'))
示例9: create_model
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [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])
示例10: create_model
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def create_model(trainable=False):
model = MobileNetV2(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3), include_top=False, alpha=ALPHA, weights="imagenet")
for layer in model.layers:
layer.trainable = trainable
block = model.get_layer("block_16_project_BN").output
x = Conv2D(112, padding="same", kernel_size=3, strides=1, activation="relu")(block)
x = Conv2D(112, padding="same", kernel_size=3, strides=1, use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation("relu")(x)
x = Conv2D(5, padding="same", kernel_size=1, activation="sigmoid")(x)
model = Model(inputs=model.input, outputs=x)
# divide by 2 since d/dweight learning_rate * weight^2 = 2 * learning_rate * weight
# see https://arxiv.org/pdf/1711.05101.pdf
regularizer = l2(WEIGHT_DECAY / 2)
for weight in model.trainable_weights:
with tf.keras.backend.name_scope("weight_regularizer"):
model.add_loss(regularizer(weight)) # in tf2.0: lambda: regularizer(weight)
return model
示例11: _keras_conv2d_core
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [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: conv_layer
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def conv_layer(inputs,
filters=32,
kernel_size=3,
strides=1,
use_maxpool=True,
postfix=None,
activation=None):
"""Helper function to build Conv2D-BN-ReLU layer
with optional MaxPooling2D.
"""
x = Conv2D(filters=filters,
kernel_size=kernel_size,
strides=strides,
kernel_initializer='he_normal',
name="conv_"+postfix,
padding='same')(inputs)
x = BatchNormalization(name="bn_"+postfix)(x)
x = Activation('relu', name='relu_'+postfix)(x)
if use_maxpool:
x = MaxPooling2D(name='pool'+postfix)(x)
return x
示例13: encoder_layer
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def encoder_layer(inputs,
filters=16,
kernel_size=3,
strides=2,
activation='relu',
instance_norm=True):
"""Builds a generic encoder layer made of Conv2D-IN-LeakyReLU
IN is optional, LeakyReLU may be replaced by ReLU
"""
conv = Conv2D(filters=filters,
kernel_size=kernel_size,
strides=strides,
padding='same')
x = inputs
if instance_norm:
x = InstanceNormalization()(x)
if activation == 'relu':
x = Activation('relu')(x)
else:
x = LeakyReLU(alpha=0.2)(x)
x = conv(x)
return x
示例14: ConvLayer
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [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
示例15: __init__
# 需要導入模塊: from tensorflow.keras import layers [as 別名]
# 或者: from tensorflow.keras.layers import Conv2D [as 別名]
def __init__(self,
filters, # NOTE: will be filters // 2
norm_type="instance",
pad_type="constant",
**kwargs):
super(BasicShuffleUnitV2, self).__init__(name="BasicShuffleUnitV2")
filters //= 2
self.model = tf.keras.models.Sequential([
Conv2D(filters, 1, use_bias=False),
get_norm(norm_type),
ReLU(),
DepthwiseConv2D(3, padding='same', use_bias=False),
get_norm(norm_type),
Conv2D(filters, 1, use_bias=False),
get_norm(norm_type),
ReLU(),
])