本文整理汇总了Python中keras.backend.int_shape方法的典型用法代码示例。如果您正苦于以下问题:Python backend.int_shape方法的具体用法?Python backend.int_shape怎么用?Python backend.int_shape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.backend
的用法示例。
在下文中一共展示了backend.int_shape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: timeception_layers
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def timeception_layers(tensor, n_layers=4, n_groups=8, is_dilated=True):
input_shape = K.int_shape(tensor)
assert len(input_shape) == 5
expansion_factor = 1.25
_, n_timesteps, side_dim, side_dim, n_channels_in = input_shape
# how many layers of timeception
for i in range(n_layers):
layer_num = i + 1
# get details about grouping
n_channels_per_branch, n_channels_out = __get_n_channels_per_branch(n_groups, expansion_factor, n_channels_in)
# temporal conv per group
tensor = __grouped_convolutions(tensor, n_groups, n_channels_per_branch, is_dilated, layer_num)
# downsample over time
tensor = MaxPooling3D(pool_size=(2, 1, 1), name='maxpool_tc%d' % (layer_num))(tensor)
n_channels_in = n_channels_out
return tensor
示例2: __call_timeception_layers
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def __call_timeception_layers(self, tensor, n_layers, n_groups, expansion_factor):
input_shape = K.int_shape(tensor)
assert len(input_shape) == 5
_, n_timesteps, side_dim, side_dim, n_channels_in = input_shape
# how many layers of timeception
for i in range(n_layers):
layer_num = i + 1
# get details about grouping
n_channels_per_branch, n_channels_out = self.__get_n_channels_per_branch(n_groups, expansion_factor, n_channels_in)
# temporal conv per group
tensor = self.__call_grouped_convolutions(tensor, n_groups, n_channels_per_branch, layer_num)
# downsample over time
tensor = getattr(self, 'maxpool_tc%d' % (layer_num))(tensor)
n_channels_in = n_channels_out
return tensor
示例3: sampling
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def sampling(args: tuple):
"""
Reparameterization trick by sampling z from unit Gaussian
:param args: (tensor, tensor) mean and log of variance of q(z|x)
:returns tensor: sampled latent vector z
"""
# unpack the input tuple
z_mean, z_log_var = args
# mini-batch size
mb_size = K.shape(z_mean)[0]
# latent space size
dim = K.int_shape(z_mean)[1]
# random normal vector with mean=0 and std=1.0
epsilon = K.random_normal(shape=(mb_size, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon
示例4: Highway
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def Highway(x, num_layers=1, activation='relu', name_prefix=''):
'''
Layer wrapper function for Highway network
# Arguments:
x: tensor, shape = (B, input_size)
# Optional Arguments:
num_layers: int, dafault is 1, the number of Highway network layers
activation: keras activation, default is 'relu'
name_prefix: str, default is '', layer name prefix
# Returns:
out: tensor, shape = (B, input_size)
'''
input_size = K.int_shape(x)[1]
for i in range(num_layers):
gate_ratio_name = '{}Highway/Gate_ratio_{}'.format(name_prefix, i)
fc_name = '{}Highway/FC_{}'.format(name_prefix, i)
gate_name = '{}Highway/Gate_{}'.format(name_prefix, i)
gate_ratio = Dense(input_size, activation='sigmoid', name=gate_ratio_name)(x)
fc = Dense(input_size, activation=activation, name=fc_name)(x)
x = Lambda(lambda args: args[0] * args[2] + args[1] * (1 - args[2]), name=gate_name)([fc, x, gate_ratio])
return x
示例5: get_constants
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def get_constants(self, x):
constants = []
if 0 < self.dropout_U < 1:
ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))
ones = K.tile(ones, (1, self.input_dim))
B_U = [K.in_train_phase(K.dropout(ones, self.dropout_U), ones) for _ in range(4)]
constants.append(B_U)
else:
constants.append([K.cast_to_floatx(1.) for _ in range(4)])
if 0 < self.dropout_W < 1:
input_shape = K.int_shape(x)
input_dim = input_shape[-1]
ones = K.ones_like(K.reshape(x[:, 0, 0], (-1, 1)))
ones = K.tile(ones, (1, int(input_dim)))
B_W = [K.in_train_phase(K.dropout(ones, self.dropout_W), ones) for _ in range(4)]
constants.append(B_W)
else:
constants.append([K.cast_to_floatx(1.) for _ in range(4)])
return constants
示例6: sampling
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def sampling(self, args):
"""Reparametrisation by sampling from Gaussian, N(0,I)
To sample from epsilon = Norm(0,I) instead of from likelihood Q(z|X)
with latent variables z: z = z_mean + sqrt(var) * epsilon
Parameters
----------
args : tensor
Mean and log of variance of Q(z|X).
Returns
-------
z : tensor
Sampled latent variable.
"""
z_mean, z_log = args
batch = K.shape(z_mean)[0] # batch size
dim = K.int_shape(z_mean)[1] # latent dimension
epsilon = K.random_normal(shape=(batch, dim)) # mean=0, std=1.0
return z_mean + K.exp(0.5 * z_log) * epsilon
示例7: call
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def call(self, inputs, training=None):
input_shape = K.int_shape(inputs)
reduction_axes = list(range(0, len(input_shape)))
if (self.axis is not None):
del reduction_axes[self.axis]
del reduction_axes[0]
mean = K.mean(inputs, reduction_axes, keepdims=True)
stddev = K.std(inputs, reduction_axes, keepdims=True) + self.epsilon
normed = (inputs - mean) / stddev
broadcast_shape = [1] * len(input_shape)
if self.axis is not None:
broadcast_shape[self.axis] = input_shape[self.axis]
if self.scale:
broadcast_gamma = K.reshape(self.gamma, broadcast_shape)
normed = normed * broadcast_gamma
if self.center:
broadcast_beta = K.reshape(self.beta, broadcast_shape)
normed = normed + broadcast_beta
return normed
示例8: VGGUpsampler
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def VGGUpsampler(pyramid, scales, classes, weight_decay=0.):
"""A Functional upsampler for the VGG Nets.
:param: pyramid: A list of features in pyramid, scaling from large
receptive field to small receptive field.
The bottom of the pyramid is the input image.
:param: scales: A list of weights for each of the feature map in the
pyramid, sorted in the same order as the pyramid.
:param: classes: Integer, number of classes.
"""
if len(scales) != len(pyramid) - 1:
raise ValueError('`scales` needs to match the length of'
'`pyramid` - 1.')
blocks = []
for i in range(len(pyramid) - 1):
block_name = 'feat{}'.format(i + 1)
block = vgg_upsampling(classes=classes,
target_shape=K.int_shape(pyramid[i + 1]),
scale=scales[i],
weight_decay=weight_decay,
block_name=block_name)
blocks.append(block)
return Decoder(pyramid=pyramid[:-1], blocks=blocks)
示例9: test_vgg_decoder
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def test_vgg_decoder():
if K.image_data_format() == 'channels_last':
inputs = Input(shape=(500, 500, 3))
pool3 = Input(shape=(88, 88, 256))
pool4 = Input(shape=(44, 44, 512))
drop7 = Input(shape=(16, 16, 4096))
score_shape = (None, 500, 500, 21)
else:
inputs = Input(shape=(3, 500, 500))
pool3 = Input(shape=(256, 88, 88))
pool4 = Input(shape=(512, 44, 44))
drop7 = Input(shape=(4096, 16, 16))
score_shape = (None, 21, 500, 500)
pyramid = [drop7, pool4, pool3, inputs]
scales = [1., 1e-2, 1e-4]
score = VGGDecoder(pyramid, scales, classes=21)
assert K.int_shape(score) == score_shape
示例10: test_vgg_conv
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def test_vgg_conv():
if K.image_data_format() == 'channels_first':
x = Input(shape=(3, 224, 224))
y1_shape = (None, 64, 112, 112)
y2_shape = (None, 128, 56, 56)
else:
x = Input(shape=(224, 224, 3))
y1_shape = (None, 112, 112, 64)
y2_shape = (None, 56, 56, 128)
block1 = vgg_conv(filters=64, convs=2, block_name='block1')
y = block1(x)
assert K.int_shape(y) == y1_shape
block2 = vgg_conv(filters=128, convs=2, block_name='block2')
y = block2(y)
assert K.int_shape(y) == y2_shape
示例11: residual
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def residual(_x, out_dim, name, stride=1):
shortcut = _x
num_channels = K.int_shape(shortcut)[-1]
_x = ZeroPadding2D(padding=1, name=name + '.pad1')(_x)
_x = Conv2D(out_dim, 3, strides=stride, use_bias=False, name=name + '.conv1')(_x)
_x = BatchNormalization(epsilon=1e-5, name=name + '.bn1')(_x)
_x = Activation('relu', name=name + '.relu1')(_x)
_x = Conv2D(out_dim, 3, padding='same', use_bias=False, name=name + '.conv2')(_x)
_x = BatchNormalization(epsilon=1e-5, name=name + '.bn2')(_x)
if num_channels != out_dim or stride != 1:
shortcut = Conv2D(out_dim, 1, strides=stride, use_bias=False, name=name + '.shortcut.0')(
shortcut)
shortcut = BatchNormalization(epsilon=1e-5, name=name + '.shortcut.1')(shortcut)
_x = Add(name=name + '.add')([_x, shortcut])
_x = Activation('relu', name=name + '.relu')(_x)
return _x
示例12: resize_image
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def resize_image(inp, s, data_format):
try:
return Lambda(lambda x: K.resize_images(x,
height_factor=s[0],
width_factor=s[1],
data_format=data_format,
interpolation='bilinear'))(inp)
except Exception as e:
# if keras is old, then rely on the tf function
# Sorry theano/cntk users!!!
assert data_format == 'channels_last'
assert IMAGE_ORDERING == 'channels_last'
import tensorflow as tf
return Lambda(
lambda x: tf.image.resize_images(
x, (K.int_shape(x)[1]*s[0], K.int_shape(x)[2]*s[1]))
)(inp)
示例13: pool_block
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def pool_block(feats, pool_factor):
if IMAGE_ORDERING == 'channels_first':
h = K.int_shape(feats)[2]
w = K.int_shape(feats)[3]
elif IMAGE_ORDERING == 'channels_last':
h = K.int_shape(feats)[1]
w = K.int_shape(feats)[2]
pool_size = strides = [
int(np.round(float(h) / pool_factor)),
int(np.round(float(w) / pool_factor))]
x = AveragePooling2D(pool_size, data_format=IMAGE_ORDERING,
strides=strides, padding='same')(feats)
x = Conv2D(512, (1, 1), data_format=IMAGE_ORDERING,
padding='same', use_bias=False)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = resize_image(x, strides, data_format=IMAGE_ORDERING)
return x
示例14: call
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def call(self, inputs, **kwargs):
if len(self._layers) == 1:
return self._layers[0](inputs)
filters = K.int_shape(inputs)[self._channel_axis]
splits = self._split_channels(filters, self.groups)
x_splits = tf.split(inputs, splits, self._channel_axis)
x_outputs = [c(x) for x, c in zip(x_splits, self._layers)]
x = layers.concatenate(x_outputs, axis=self._channel_axis)
return x
示例15: __call__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import int_shape [as 别名]
def __call__(self, inputs):
filters = K.int_shape(inputs)[self._channel_axis]
grouped_op = GroupConvolution(filters, self.kernels, groups=len(self.kernels),
type='depthwise_conv', conv_kwargs=self._conv_kwargs)
x = grouped_op(inputs)
return x
# Obtained from https://github.com/tensorflow/tpu/blob/master/models/official/mnasnet/mixnet/mixnet_model.py