本文整理汇总了Python中keras.backend.variable方法的典型用法代码示例。如果您正苦于以下问题:Python backend.variable方法的具体用法?Python backend.variable怎么用?Python backend.variable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.backend
的用法示例。
在下文中一共展示了backend.variable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def build(self, input_shape):
self.input_spec = [InputSpec(shape=input_shape)]
self.input_dim = input_shape[2]
self.W = self.init((self.output_dim, 4 * self.input_dim),
name='{}_W'.format(self.name))
self.U = self.inner_init((self.input_dim, 4 * self.input_dim),
name='{}_U'.format(self.name))
self.b = K.variable(np.hstack((np.zeros(self.input_dim),
K.get_value(self.forget_bias_init((self.input_dim,))),
np.zeros(self.input_dim),
np.zeros(self.input_dim))),
name='{}_b'.format(self.name))
self.A = self.init((self.input_dim, self.output_dim),
name='{}_A'.format(self.name))
self.ba = K.zeros((self.output_dim,), name='{}_ba'.format(self.name))
self.trainable_weights = [self.W, self.U, self.b, self.A, self.ba]
if self.initial_weights is not None:
self.set_weights(self.initial_weights)
del self.initial_weights
示例2: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999,
epsilon=None, decay=0., amsgrad=False, accum_iters=1, **kwargs):
if accum_iters < 1:
raise ValueError('accum_iters must be >= 1')
super(AdamAccumulate, self).__init__(**kwargs)
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.beta_1 = K.variable(beta_1, name='beta_1')
self.beta_2 = K.variable(beta_2, name='beta_2')
self.decay = K.variable(decay, name='decay')
if epsilon is None:
epsilon = K.epsilon()
self.epsilon = epsilon
self.initial_decay = decay
self.amsgrad = amsgrad
self.accum_iters = K.variable(accum_iters, K.dtype(self.iterations))
self.accum_iters_float = K.cast(self.accum_iters, K.floatx())
示例3: get_total_loss
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def get_total_loss(content_losses, style_losses, total_var_loss,
content_weights, style_weights, tv_weights, class_targets):
total_loss = K.variable(0.)
# Compute content losses
for loss in content_losses:
weighted_loss = K.mean(K.gather(content_weights, class_targets) * loss)
weighted_content_losses.append(weighted_loss)
total_loss += weighted_loss
# Compute style losses
for loss in style_losses:
weighted_loss = K.mean(K.gather(style_weights, class_targets) * loss)
weighted_style_losses.append(weighted_loss)
total_loss += weighted_loss
# Compute tv loss
weighted_tv_loss = K.mean(K.gather(tv_weights, class_targets) *
total_var_loss)
total_loss += weighted_tv_loss
return (total_loss, weighted_content_losses, weighted_style_losses,
weighted_tv_loss)
示例4: build
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def build(self, input_shape):
# Create mean and count
# These are weights because just maintaining variables don't get saved with the model, and we'd like
# to have these numbers saved when we save the model.
# But we need to make sure that the weights are untrainable.
self.mean = self.add_weight(name='mean',
shape=input_shape[1:],
initializer='zeros',
trainable=False)
self.count = self.add_weight(name='count',
shape=[1],
initializer='zeros',
trainable=False)
# self.mean = K.zeros(input_shape[1:], name='mean')
# self.count = K.variable(0.0, name='count')
super(MeanStream, self).build(input_shape) # Be sure to call this somewhere!
示例5: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self, lr=0.001, final_lr=0.1, beta_1=0.9, beta_2=0.999, gamma=1e-3,
epsilon=None, decay=0., amsbound=False, weight_decay=0.0, **kwargs):
super(AdaBound, self).__init__(**kwargs)
if not 0. <= gamma <= 1.:
raise ValueError("Invalid `gamma` parameter. Must lie in [0, 1] range.")
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.beta_1 = K.variable(beta_1, name='beta_1')
self.beta_2 = K.variable(beta_2, name='beta_2')
self.decay = K.variable(decay, name='decay')
self.final_lr = final_lr
self.gamma = gamma
if epsilon is None:
epsilon = K.epsilon()
self.epsilon = epsilon
self.initial_decay = decay
self.amsbound = amsbound
self.weight_decay = float(weight_decay)
self.base_lr = float(lr)
示例6: find_analogy_patches
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def find_analogy_patches(a, a_prime, b, patch_size=3, patch_stride=1):
'''This is for precalculating the analogy_loss
Since A, A', and B never change we only need to calculate the patch matches once.
'''
# extract patches from feature maps
a_patches, a_patches_norm = patches.make_patches(K.variable(a), patch_size, patch_stride)
a_prime_patches, a_prime_patches_norm = patches.make_patches(K.variable(a_prime), patch_size, patch_stride)
b_patches, b_patches_norm = patches.make_patches(K.variable(b), patch_size, patch_stride)
# find best patches and calculate loss
p = patches.find_patch_matches(b_patches, b_patches_norm, a_patches / a_patches_norm)
#best_patches = a_prime_patches[p]
best_patches = K.reshape(a_prime_patches[p], K.shape(b_patches))
f = K.function([], best_patches)
best_patches = f([])
return best_patches
示例7: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self, lr=1e-1, beta_1=0.9, beta_2=0.999,
epsilon=1e-8, decay=0., amsgrad=False, partial=1. / 8., **kwargs):
if partial < 0 or partial > 0.5:
raise ValueError(
"Padam: 'partial' must be a positive float with a maximum "
"value of `0.5`, since higher values will cause divergence "
"during training."
)
super(Padam, self).__init__(**kwargs)
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.beta_1 = K.variable(beta_1, name='beta_1')
self.beta_2 = K.variable(beta_2, name='beta_2')
self.decay = K.variable(decay, name='decay')
if epsilon is None:
epsilon = K.epsilon()
self.epsilon = epsilon
self.partial = partial
self.initial_decay = decay
self.amsgrad = amsgrad
示例8: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self,
lr,
momentum=0.9,
weight_decay=0.0001,
eeta=0.001,
epsilon=0.0,
nesterov=False,
**kwargs):
if momentum < 0.0:
raise ValueError("momentum should be positive: %s" % momentum)
if weight_decay < 0.0:
raise ValueError("weight_decay is not positive: %s" % weight_decay)
super(LARS, self).__init__(**kwargs)
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.momentum = K.variable(momentum, name='momentum')
self.weight_decay = K.variable(weight_decay, name='weight_decay')
self.eeta = K.variable(eeta, name='eeta')
self.epsilon = epsilon
self.nesterov = nesterov
示例9: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self, lr=0.01, beta_1=0.9, beta_2=0.999,
epsilon=1e-3, decay=0., **kwargs):
super(Yogi, self).__init__(**kwargs)
if beta_1 <= 0 or beta_1 >= 1:
raise ValueError("beta_1 has to be in ]0, 1[")
if beta_2 <= 0 or beta_2 >= 1:
raise ValueError("beta_2 has to be in ]0, 1[")
with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
self.lr = K.variable(lr, name='lr')
self.beta_1 = K.variable(beta_1, name='beta_1')
self.beta_2 = K.variable(beta_2, name='beta_2')
self.decay = K.variable(decay, name='decay')
if epsilon is None:
epsilon = K.epsilon()
if epsilon <= 0:
raise ValueError("epsilon has to be larger than 0")
self.epsilon = epsilon
self.initial_decay = decay
示例10: test_sub_pixel_upscaling
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def test_sub_pixel_upscaling(scale_factor):
num_samples = 2
num_row = 16
num_col = 16
input_dtype = K.floatx()
nb_channels = 4 * (scale_factor ** 2)
input_data = np.random.random((num_samples, nb_channels, num_row, num_col))
input_data = input_data.astype(input_dtype)
if K.image_data_format() == 'channels_last':
input_data = input_data.transpose((0, 2, 3, 1))
input_tensor = K.variable(input_data)
expected_output = K.eval(KC.depth_to_space(input_tensor,
scale=scale_factor))
layer_test(SubPixelUpscaling,
kwargs={'scale_factor': scale_factor},
input_data=input_data,
expected_output=expected_output,
expected_output_dtype=K.floatx())
示例11: check_composed_tensor_operations
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def check_composed_tensor_operations(first_function_name, first_function_args,
second_function_name, second_function_args,
input_shape):
''' Creates a random tensor t0 with shape input_shape and compute
t1 = first_function_name(t0, **first_function_args)
t2 = second_function_name(t1, **second_function_args)
with both Theano and TensorFlow backends and ensures the answers match.
'''
val = np.random.random(input_shape) - 0.5
xth = KTH.variable(val)
xtf = KTF.variable(val)
yth = getattr(KCTH, first_function_name)(xth, **first_function_args)
ytf = getattr(KCTF, first_function_name)(xtf, **first_function_args)
zth = KTH.eval(getattr(KCTH, second_function_name)(yth, **second_function_args))
ztf = KTF.eval(getattr(KCTF, second_function_name)(ytf, **second_function_args))
assert zth.shape == ztf.shape
assert_allclose(zth, ztf, atol=1e-05)
示例12: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self, s=3, skip=True):
self.skip = skip
self.s = K.variable(s, name='s_constraint')
示例13: __init__
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def __init__(self):
self.gamma = K.variable(2.)
示例14: yolo_eval
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def yolo_eval(yolo_outputs,
image_shape,
max_boxes=10,
score_threshold=.6,
iou_threshold=.5):
"""Evaluate YOLO model on given input batch and return filtered boxes."""
box_xy, box_wh, box_confidence, box_class_probs = yolo_outputs
boxes = yolo_boxes_to_corners(box_xy, box_wh)
boxes, scores, classes = yolo_filter_boxes(
boxes, box_confidence, box_class_probs, threshold=score_threshold)
# Scale boxes back to original image shape.
height = image_shape[0]
width = image_shape[1]
image_dims = K.stack([height, width, height, width])
image_dims = K.reshape(image_dims, [1, 4])
boxes = boxes * image_dims
# TODO: Something must be done about this ugly hack!
max_boxes_tensor = K.variable(max_boxes, dtype='int32')
K.get_session().run(tf.variables_initializer([max_boxes_tensor]))
nms_index = tf.image.non_max_suppression(
boxes, scores, max_boxes_tensor, iou_threshold=iou_threshold)
boxes = K.gather(boxes, nms_index)
scores = K.gather(scores, nms_index)
classes = K.gather(classes, nms_index)
return boxes, scores, classes
示例15: build
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import variable [as 别名]
def build(self, input_shape):
self.input_spec = [InputSpec(shape=input_shape)]
shape = (int(input_shape[self.axis]),)
self.gamma = K.variable(self.gamma_init(shape), name='%s_gamma' % self.name)
self.beta = K.variable(self.beta_init(shape), name='%s_beta' % self.name)
self.trainable_weights = [self.gamma, self.beta]
if self.initial_weights is not None:
self.set_weights(self.initial_weights)
del self.initial_weights