本文整理汇总了Python中keras.backend.eval方法的典型用法代码示例。如果您正苦于以下问题:Python backend.eval方法的具体用法?Python backend.eval怎么用?Python backend.eval使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.backend
的用法示例。
在下文中一共展示了backend.eval方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_config
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def get_config(self):
config = {
'lr': float(K.get_value(self.lr)),
'beta_1': float(K.get_value(self.beta_1)),
'beta_2': float(K.get_value(self.beta_2)),
'decay': float(K.get_value(self.decay)),
'batch_size': int(self.batch_size),
'total_iterations': int(self.total_iterations),
'weight_decays': self.weight_decays,
'lr_multipliers': self.lr_multipliers,
'use_cosine_annealing': self.use_cosine_annealing,
't_cur': int(K.get_value(self.t_cur)),
'eta_t': float(K.eval(self.eta_t)),
'eta_min': float(K.get_value(self.eta_min)),
'eta_max': float(K.get_value(self.eta_max)),
'init_verbose': self.init_verbose,
'epsilon': self.epsilon,
'amsgrad': self.amsgrad
}
base_config = super(AdamW, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
示例2: save_tmp_func
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def save_tmp_func(self, step):
cur_mask = K.eval(self.mask_upsample_tensor)
cur_mask = cur_mask[0, ..., 0]
img_filename = (
'%s/%s' % (self.tmp_dir, 'tmp_mask_step_%d.png' % step))
utils_backdoor.dump_image(np.expand_dims(cur_mask, axis=2) * 255,
img_filename,
'png')
cur_fusion = K.eval(self.mask_upsample_tensor *
self.pattern_raw_tensor)
cur_fusion = cur_fusion[0, ...]
img_filename = (
'%s/%s' % (self.tmp_dir, 'tmp_fusion_step_%d.png' % step))
utils_backdoor.dump_image(cur_fusion, img_filename, 'png')
pass
示例3: test_switchnorm_convnet
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_switchnorm_convnet():
model = Sequential()
norm = SwitchNormalization(axis=1, input_shape=(3, 4, 4), momentum=0.8)
model.add(norm)
model.compile(loss='mse', optimizer='sgd')
# centered on 5.0, variance 10.0
np.random.seed(123)
x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 3, 4, 4))
model.fit(x, x, epochs=4, verbose=0)
out = model.predict(x)
out -= np.reshape(K.eval(norm.beta), (1, 3, 1, 1))
out /= np.reshape(K.eval(norm.gamma), (1, 3, 1, 1))
assert_allclose(np.mean(out, axis=(0, 2, 3)), 0.0, atol=1e-1)
assert_allclose(np.std(out, axis=(0, 2, 3)), 1.0, atol=1e-1)
示例4: evaluate
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def evaluate(self, inputs, fn_inverse=None, fn_plot=None):
try:
X, y = inputs
inputs = X
except:
X, conditions, y = inputs
inputs = [X, conditions]
y_hat = self.predict(inputs)
if fn_inverse is not None:
y_hat = fn_inverse(y_hat)
y = fn_inverse(y)
if fn_plot is not None:
fn_plot([y, y_hat])
results = []
for m in self.model.metrics:
if isinstance(m, str):
results.append(K.eval(K.mean(get(m)(y, y_hat))))
else:
results.append(K.eval(K.mean(m(y, y_hat))))
return results
示例5: test_instancenorm_perinstancecorrectness
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_instancenorm_perinstancecorrectness():
model = Sequential()
norm = InstanceNormalization(input_shape=(10,))
model.add(norm)
model.compile(loss='mse', optimizer='sgd')
# bimodal distribution
z = np.random.normal(loc=5.0, scale=10.0, size=(2, 10))
y = np.random.normal(loc=-5.0, scale=17.0, size=(2, 10))
x = np.append(z, y)
x = np.reshape(x, (4, 10))
model.fit(x, x, epochs=4, batch_size=4, verbose=1)
out = model.predict(x)
out -= K.eval(norm.beta)
out /= K.eval(norm.gamma)
# verify that each instance in the batch is individually normalized
for i in range(4):
instance = out[i]
assert_allclose(instance.mean(), 0.0, atol=1e-1)
assert_allclose(instance.std(), 1.0, atol=1e-1)
# if each instance is normalized, so should the batch
assert_allclose(out.mean(), 0.0, atol=1e-1)
assert_allclose(out.std(), 1.0, atol=1e-1)
示例6: test_groupnorm_convnet
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_groupnorm_convnet():
model = Sequential()
norm = GroupNormalization(axis=1,
input_shape=(3, 4, 4),
groups=3)
model.add(norm)
model.compile(loss='mse', optimizer='sgd')
# centered on 5.0, variance 10.0
x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 3, 4, 4))
model.fit(x, x, epochs=4, verbose=0)
out = model.predict(x)
out -= np.reshape(K.eval(norm.beta), (1, 3, 1, 1))
out /= np.reshape(K.eval(norm.gamma), (1, 3, 1, 1))
assert_allclose(np.mean(out, axis=(0, 2, 3)), 0.0, atol=1e-1)
assert_allclose(np.std(out, axis=(0, 2, 3)), 1.0, atol=1e-1)
示例7: test_sub_pixel_upscaling
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [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())
示例8: check_composed_tensor_operations
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [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)
示例9: test_extract2
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_extract2(self, input_shape, kernel_shape):
xval = np.random.random(input_shape)
kernel = [kernel_shape, kernel_shape]
strides = [kernel_shape, kernel_shape]
xth = KTH.variable(xval)
xtf = KTF.variable(xval)
ztf = KTF.eval(KCTF.extract_image_patches(xtf, kernel, strides,
data_format='channels_last',
padding='same'))
zth = KTH.eval(KCTH.extract_image_patches(xth, kernel, strides,
data_format='channels_last',
padding='same'))
assert zth.shape == ztf.shape
assert_allclose(zth, ztf, atol=1e-02)
示例10: test_moments
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_moments(self, keep_dims):
input_shape = (10, 10, 10, 10)
x_0 = np.zeros(input_shape)
x_1 = np.ones(input_shape)
x_random = np.random.random(input_shape)
th_axes = [0, 2, 3]
tf_axes = [0, 1, 2]
for ip in [x_0, x_1, x_random]:
for axes in [th_axes, tf_axes]:
K_mean, K_var = KC.moments(K.variable(ip), axes, keep_dims=keep_dims)
np_mean, np_var = KCNP.moments(ip, axes, keep_dims=keep_dims)
K_mean_val = K.eval(K_mean)
K_var_val = K.eval(K_var)
# absolute tolerance needed when working with zeros
assert_allclose(K_mean_val, np_mean, rtol=1e-4, atol=1e-10)
assert_allclose(K_var_val, np_var, rtol=1e-4, atol=1e-10)
示例11: test_matching_layers
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_matching_layers():
s1_value = np.array([[[1, 2], [2, 3], [3, 4]],
[[0.1, 0.2], [0.2, 0.3], [0.3, 0.4]]
])
s2_value = np.array([[[1, 2], [2, 3]],
[[0.1, 0.2], [0.2, 0.3]]
])
s3_value = np.array([[[1, 2], [2, 3]],
[[0.1, 0.2], [0.2, 0.3]],
[[0.1, 0.2], [0.2, 0.3]]
])
s1_tensor = K.variable(s1_value)
s2_tensor = K.variable(s2_value)
s3_tensor = K.variable(s3_value)
for matching_type in ['dot', 'mul', 'plus', 'minus', 'concat']:
model = layers.MatchingLayer(matching_type=matching_type)([s1_tensor, s2_tensor])
ret = K.eval(model)
with pytest.raises(ValueError):
layers.MatchingLayer(matching_type='error')
with pytest.raises(ValueError):
layers.MatchingLayer()([s1_tensor, s3_tensor])
示例12: test_matching_tensor_layer
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_matching_tensor_layer():
s1_value = np.array([[[1, 2], [2, 3], [3, 4]],
[[0.1, 0.2], [0.2, 0.3], [0.3, 0.4]]])
s2_value = np.array([[[1, 2], [2, 3]],
[[0.1, 0.2], [0.2, 0.3]]])
s3_value = np.array([[[1, 2], [2, 3]],
[[0.1, 0.2], [0.2, 0.3]],
[[0.1, 0.2], [0.2, 0.3]]])
s1_tensor = K.variable(s1_value)
s2_tensor = K.variable(s2_value)
s3_tensor = K.variable(s3_value)
for init_diag in [True, False]:
model = MatchingTensorLayer(init_diag=init_diag)
_ = K.eval(model([s1_tensor, s2_tensor]))
with pytest.raises(ValueError):
MatchingTensorLayer()([s1_tensor, s3_tensor])
示例13: test_hinge_loss
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_hinge_loss():
true_value = K.variable(np.array([[1.2], [1],
[1], [1]]))
pred_value = K.variable(np.array([[1.2], [0.1],
[0], [-0.3]]))
expected_loss = (0 + 1 - 0.3 + 0) / 2.0
loss = K.eval(losses.RankHingeLoss()(true_value, pred_value))
assert np.isclose(expected_loss, loss)
expected_loss = (2 + 0.1 - 1.2 + 2 - 0.3 + 0) / 2.0
loss = K.eval(losses.RankHingeLoss(margin=2)(true_value, pred_value))
assert np.isclose(expected_loss, loss)
true_value = K.variable(np.array([[1.2], [1], [0.8],
[1], [1], [0.8]]))
pred_value = K.variable(np.array([[1.2], [0.1], [-0.5],
[0], [0], [-0.3]]))
expected_loss = (0 + 1 - 0.15) / 2.0
loss = K.eval(losses.RankHingeLoss(num_neg=2, margin=1)(
true_value, pred_value))
assert np.isclose(expected_loss, loss)
示例14: test_max_norm
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def test_max_norm():
array = get_example_array()
for m in get_test_values():
norm_instance = constraints.max_norm(m)
normed = norm_instance(K.variable(array))
assert(np.all(K.eval(normed) < m))
# a more explicit example
norm_instance = constraints.max_norm(2.0)
x = np.array([[0, 0, 0], [1.0, 0, 0], [3, 0, 0], [3, 3, 3]]).T
x_normed_target = np.array([[0, 0, 0], [1.0, 0, 0],
[2.0, 0, 0],
[2. / np.sqrt(3),
2. / np.sqrt(3),
2. / np.sqrt(3)]]).T
x_normed_actual = K.eval(norm_instance(K.variable(x)))
assert_allclose(x_normed_actual, x_normed_target, rtol=1e-05)
示例15: on_epoch_end
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import eval [as 别名]
def on_epoch_end(self, epoch, logs=None):
logs.update({'lr': K.eval(self.model.optimizer.lr)})
super().on_epoch_end(epoch, logs)