本文整理汇总了Python中keras.backend.image_dim_ordering方法的典型用法代码示例。如果您正苦于以下问题:Python backend.image_dim_ordering方法的具体用法?Python backend.image_dim_ordering怎么用?Python backend.image_dim_ordering使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.backend
的用法示例。
在下文中一共展示了backend.image_dim_ordering方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rpn_loss_regr
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def rpn_loss_regr(num_anchors):
def rpn_loss_regr_fixed_num(y_true, y_pred):
if K.image_dim_ordering() == 'th':
x = y_true[:, 4 * num_anchors:, :, :] - y_pred
x_abs = K.abs(x)
x_bool = K.less_equal(x_abs, 1.0)
return lambda_rpn_regr * K.sum(
y_true[:, :4 * num_anchors, :, :] * (x_bool * (0.5 * x * x) + (1 - x_bool) * (x_abs - 0.5))) / K.sum(epsilon + y_true[:, :4 * num_anchors, :, :])
else:
x = y_true[:, :, :, 4 * num_anchors:] - y_pred
x_abs = K.abs(x)
x_bool = K.cast(K.less_equal(x_abs, 1.0), tf.float32)
return lambda_rpn_regr * K.sum(
y_true[:, :, :, :4 * num_anchors] * (x_bool * (0.5 * x * x) + (1 - x_bool) * (x_abs - 0.5))) / K.sum(epsilon + y_true[:, :, :, :4 * num_anchors])
return rpn_loss_regr_fixed_num
示例2: _load_features
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def _load_features(self, audio_filename):
features = list()
for feature_filename in self.feature_filenames:
if audio_filename in feature_filename:
filename_full_path = os.path.join(IRMAS_TEST_FEATURE_BASEPATH,
self.model_module.BASE_NAME,
feature_filename)
feature = np.load(filename_full_path)
feature -= self.dataset_mean
features.append(feature)
if K.image_dim_ordering() == "th":
features = np.array(features).reshape(-1, 1, self.model_module.N_MEL_BANDS, self.model_module.SEGMENT_DUR)
else:
features = np.array(features).reshape(-1, self.model_module.N_MEL_BANDS, self.model_module.SEGMENT_DUR, 1)
return features
示例3: deprocess_image
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def deprocess_image(x):
""" Same normalization as in:
https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py
"""
if np.ndim(x) > 3:
x = np.squeeze(x)
# normalize tensor: center on 0., ensure std is 0.1
x = x - x.mean()
x = x / (x.std() + 1e-5)
x = x * 0.1
# clip to [0, 1]
x = x + 0.5
x = np.clip(x, 0, 1)
# convert to RGB array
x = x * 255
if K.image_dim_ordering() == 'th':
x = x.transpose((1, 2, 0))
x = np.clip(x, 0, 255).astype('uint8')
return x
示例4: preprocess_input
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def preprocess_input(x, dim_ordering='default'):
if dim_ordering == 'default':
dim_ordering = K.image_dim_ordering()
assert dim_ordering in {'tf', 'th'}
if dim_ordering == 'th':
x[:, 0, :, :] -= 103.939
x[:, 1, :, :] -= 116.779
x[:, 2, :, :] -= 123.68
# 'RGB'->'BGR'
x = x[:, ::-1, :, :]
else:
x[:, :, :, 0] -= 103.939
x[:, :, :, 1] -= 116.779
x[:, :, :, 2] -= 123.68
# 'RGB'->'BGR'
x = x[:, :, :, ::-1]
return x
示例5: conv2d_bn
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def conv2d_bn(x, nb_filter, nb_row, nb_col,
border_mode='same', subsample=(1, 1),
name=None):
'''Utility function to apply conv + BN.
'''
if name is not None:
bn_name = name + '_bn'
conv_name = name + '_conv'
else:
bn_name = None
conv_name = None
if K.image_dim_ordering() == 'th':
bn_axis = 1
else:
bn_axis = 3
x = Convolution2D(nb_filter, nb_row, nb_col,
subsample=subsample,
activation='relu',
border_mode=border_mode,
name=conv_name)(x)
x = BatchNormalization(axis=bn_axis, name=bn_name)(x)
return x
示例6: build_vgg16
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def build_vgg16(image_size=None):
image_size = image_size or (240, 240)
if K.image_dim_ordering() == 'th':
input_shape = (3,) + image_size
else:
input_shape = image_size + (3, )
bottleneck_model = vgg16.VGG16(include_top=False,
input_tensor=Input(input_shape))
#bottleneck_model.trainable = False
for layer in bottleneck_model.layers:
layer.trainable = False
x = bottleneck_model.input
y = bottleneck_model.output
y = Flatten()(y)
y = BatchNormalization()(y)
y = Dense(2048, activation='relu')(y)
y = Dropout(.5)(y)
y = Dense(1024, activation='relu')(y)
y = Dropout(.5)(y)
y = Dense(1)(y)
model = Model(input=x, output=y)
model.compile(optimizer=Adam(lr=1e-4), loss = 'mse')
return model
示例7: array_to_img
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def array_to_img(x, dim_ordering='default', scale=True):
from PIL import Image
if dim_ordering == 'default':
dim_ordering = K.image_dim_ordering()
if dim_ordering == 'th':
x = x.transpose(1, 2, 0)
if scale:
x += max(-np.min(x), 0)
x_max = np.max(x)
if x_max != 0:
x /= x_max
x *= 255
if x.shape[2] == 3:
# RGB
return Image.fromarray(x.astype('uint8'), 'RGB')
elif x.shape[2] == 1:
# grayscale
return Image.fromarray(x[:, :, 0].astype('uint8'), 'L')
else:
raise Exception('Unsupported channel number: ', x.shape[2])
示例8: img_to_array
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def img_to_array(img, dim_ordering='default'):
if dim_ordering == 'default':
dim_ordering = K.image_dim_ordering()
if dim_ordering not in ['th', 'tf']:
raise Exception('Unknown dim_ordering: ', dim_ordering)
# image has dim_ordering (height, width, channel)
x = np.asarray(img, dtype='float32')
if len(x.shape) == 3:
if dim_ordering == 'th':
x = x.transpose(2, 0, 1)
elif len(x.shape) == 2:
if dim_ordering == 'th':
x = x.reshape((1, x.shape[0], x.shape[1]))
else:
x = x.reshape((x.shape[0], x.shape[1], 1))
else:
raise Exception('Unsupported image shape: ', x.shape)
return x
示例9: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def __init__(self, X, y, image_data_generator,
batch_size=32, shuffle=False, seed=None,
dim_ordering='default',
save_to_dir=None, save_prefix='', save_format='jpeg'):
if y is not None and len(X) != len(y):
raise Exception('X (images tensor) and y (labels) '
'should have the same length. '
'Found: X.shape = %s, y.shape = %s' % (np.asarray(X).shape, np.asarray(y).shape))
if dim_ordering == 'default':
dim_ordering = K.image_dim_ordering()
self.X = X
self.y = y
self.image_data_generator = image_data_generator
self.dim_ordering = dim_ordering
self.save_to_dir = save_to_dir
self.save_prefix = save_prefix
self.save_format = save_format
super(NumpyArrayIterator, self).__init__(X.shape[0], batch_size, shuffle, seed)
示例10: call
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def call(self, x, mask=None):
if K.image_dim_ordering == "th":
_, f, r, c = self.shape
else:
_, r, c, f = self.shape
squared = K.square(x)
pooled = K.pool2d(squared, (self.n, self.n), strides=(1, 1),
padding="same", pool_mode="avg")
if K.image_dim_ordering == "th":
summed = K.sum(pooled, axis=1, keepdims=True)
averaged = self.alpha * K.repeat_elements(summed, f, axis=1)
else:
summed = K.sum(pooled, axis=3, keepdims=True)
averaged = self.alpha * K.repeat_elements(summed, f, axis=3)
denom = K.pow(self.k + averaged, self.beta)
return x / denom
示例11: transition_block
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def transition_block(ip, nb_filter, dropout_rate=None, weight_decay=1E-4):
''' Apply BatchNorm, Relu 1x1, Conv2D, optional dropout and Maxpooling2D
Args:
ip: keras tensor
nb_filter: number of filters
dropout_rate: dropout rate
weight_decay: weight decay factor
Returns: keras tensor, after applying batch_norm, relu-conv, dropout, maxpool
'''
concat_axis = 1 if K.image_dim_ordering() == "th" else -1
x = Convolution2D(nb_filter, 1, 1, init="he_uniform", border_mode="same", bias=False,
W_regularizer=l2(weight_decay))(ip)
if dropout_rate:
x = Dropout(dropout_rate)(x)
x = AveragePooling2D((2, 2), strides=(2, 2))(x)
x = BatchNormalization(mode=0, axis=concat_axis, gamma_regularizer=l2(weight_decay),
beta_regularizer=l2(weight_decay))(x)
return x
示例12: predict
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def predict(self, image, img_channels=3):
if K.image_dim_ordering() == 'th' and image.shape != (1,img_channels, IMAGE_SIZE, IMAGE_SIZE):
image = resize_with_pad(image)
image = image.reshape((1, img_channels, IMAGE_SIZE, IMAGE_SIZE))
elif K.image_dim_ordering() == 'tf' and image.shape != (1, IMAGE_SIZE, IMAGE_SIZE, img_channels):
image = resize_with_pad(image)
image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, img_channels))
image = image.astype('float32')
image /= 255
if DEBUG_MUTE:
result = self.model.predict_proba(image, verbose=0)
result = self.model.predict_classes(image, verbose=0)
else:
result = self.model.predict_proba(image)
print(result)
result = self.model.predict_classes(image)
print(result)
return result[0]
示例13: rpn_loss_regr
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def rpn_loss_regr(num_anchors):
def rpn_loss_regr_fixed_num(y_true, y_pred):
if K.image_dim_ordering() == 'th':
x = y_true[:, 4 * num_anchors:, :, :] - y_pred
x_abs = K.abs(x)
x_bool = K.less_equal(x_abs, 1.0)
return lambda_rpn_regr * K.sum(
y_true[:, :4 * num_anchors, :, :] * (x_bool * (0.5 * x * x) + (1 - x_bool) * (x_abs - 0.5))) / K.sum(epsilon + y_true[:, :4 * num_anchors, :, :])
else:
x = y_true[:, :, :, 4 * num_anchors:] - y_pred
x_abs = K.abs(x)
x_bool = K.cast(K.less_equal(x_abs, 1.0), tf.float32)
return lambda_rpn_regr * K.sum(
y_true[:, :, :, :4 * num_anchors] * (x_bool * (0.5 * x * x) + (1 - x_bool) * (x_abs - 0.5))) / K.sum(epsilon + y_true[:, :, :, :4 * num_anchors])
return rpn_loss_regr_fixed_num
示例14: get_feature_map_4
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def get_feature_map_4(model, im):
im = im.astype(np.float32)
dim_ordering = K.image_dim_ordering()
if dim_ordering == 'th':
# 'RGB'->'BGR'
im = im[::-1, :, :]
# Zero-center by mean pixel
im[0, :, :] -= 103.939
im[1, :, :] -= 116.779
im[2, :, :] -= 123.68
else:
# 'RGB'->'BGR'
im = im[:, :, ::-1]
# Zero-center by mean pixel
im[:, :, 0] -= 103.939
im[:, :, 1] -= 116.779
im[:, :, 2] -= 123.68
im = im.transpose((2, 0, 1))
im = np.expand_dims(im, axis=0)
inputs = [K.learning_phase()] + model.inputs
_convout1_f = K.function(inputs, [model.layers[23].output])
feature_map = _convout1_f([0] + [im])
feature_map = np.array([feature_map])
feature_map = feature_map[0, 0, 0, :, :, :]
return feature_map
示例15: get_image_descriptor_for_image
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import image_dim_ordering [as 别名]
def get_image_descriptor_for_image(image, model):
im = cv2.resize(image, (224, 224)).astype(np.float32)
dim_ordering = K.image_dim_ordering()
if dim_ordering == 'th':
# 'RGB'->'BGR'
im = im[::-1, :, :]
# Zero-center by mean pixel
im[0, :, :] -= 103.939
im[1, :, :] -= 116.779
im[2, :, :] -= 123.68
else:
# 'RGB'->'BGR'
im = im[:, :, ::-1]
# Zero-center by mean pixel
im[:, :, 0] -= 103.939
im[:, :, 1] -= 116.779
im[:, :, 2] -= 123.68
im = im.transpose((2, 0, 1))
im = np.expand_dims(im, axis=0)
inputs = [K.learning_phase()] + model.inputs
_convout1_f = K.function(inputs, [model.layers[33].output])
return _convout1_f([0] + [im])