本文整理汇总了Python中keras.backend.square方法的典型用法代码示例。如果您正苦于以下问题:Python backend.square方法的具体用法?Python backend.square怎么用?Python backend.square使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类keras.backend
的用法示例。
在下文中一共展示了backend.square方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_pattern
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def generate_pattern(layer_name, filter_index, size=150):
# 过滤器可视化函数
layer_output = model.get_layer(layer_name).output
loss = K.mean(layer_output[:, :, :, filter_index])
grads = K.gradients(loss, model.input)[0]
grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5)
iterate = K.function([model.input], [loss, grads])
input_img_data = np.random.random((1, size, size, 3)) * 20 + 128.
step = 1
for _ in range(40):
loss_value, grads_value = iterate([input_img_data])
input_img_data += grads_value * step
img = input_img_data[0]
return deprocess_image(img)
示例2: gradient_penalty_loss
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def gradient_penalty_loss(self, y_true, y_pred, averaged_samples):
"""
Computes gradient penalty based on prediction and weighted real / fake samples
"""
gradients = K.gradients(y_pred, averaged_samples)[0]
# compute the euclidean norm by squaring ...
gradients_sqr = K.square(gradients)
# ... summing over the rows ...
gradients_sqr_sum = K.sum(gradients_sqr,
axis=np.arange(1, len(gradients_sqr.shape)))
# ... and sqrt
gradient_l2_norm = K.sqrt(gradients_sqr_sum)
# compute lambda * (1 - ||grad||)^2 still for each single sample
gradient_penalty = K.square(1 - gradient_l2_norm)
# return the mean as loss over all the batch samples
return K.mean(gradient_penalty)
示例3: audio_discriminate_loss2
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def audio_discriminate_loss2(gamma=0.1,beta = 2*0.1,num_speaker=2):
def loss_func(S_true,S_pred,gamma=gamma,beta=beta,num_speaker=num_speaker):
sum_mtr = K.zeros_like(S_true[:,:,:,:,0])
for i in range(num_speaker):
sum_mtr += K.square(S_true[:,:,:,:,i]-S_pred[:,:,:,:,i])
for j in range(num_speaker):
if i != j:
sum_mtr -= gamma*(K.square(S_true[:,:,:,:,i]-S_pred[:,:,:,:,j]))
for i in range(num_speaker):
for j in range(i+1,num_speaker):
#sum_mtr -= beta*K.square(S_pred[:,:,:,i]-S_pred[:,:,:,j])
#sum_mtr += beta*K.square(S_true[:,:,:,:,i]-S_true[:,:,:,:,j])
pass
#sum = K.sum(K.maximum(K.flatten(sum_mtr),0))
loss = K.mean(K.flatten(sum_mtr))
return loss
return loss_func
示例4: optimizer
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def optimizer(self):
a = K.placeholder(shape=(None,), dtype='int32')
y = K.placeholder(shape=(None,), dtype='float32')
prediction = self.model.output
a_one_hot = K.one_hot(a, self.action_size)
q_value = K.sum(prediction * a_one_hot, axis=1)
error = K.abs(y - q_value)
quadratic_part = K.clip(error, 0.0, 1.0)
linear_part = error - quadratic_part
loss = K.mean(0.5 * K.square(quadratic_part) + linear_part)
optimizer = RMSprop(lr=0.00025, epsilon=0.01)
updates = optimizer.get_updates(self.model.trainable_weights, [], loss)
train = K.function([self.model.input, a, y], [loss], updates=updates)
return train
# 상태가 입력, 큐함수가 출력인 인공신경망 생성
示例5: optimizer
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def optimizer(self):
a = K.placeholder(shape=(None, ), dtype='int32')
y = K.placeholder(shape=(None, ), dtype='float32')
py_x = self.model.output
a_one_hot = K.one_hot(a, self.action_size)
q_value = K.sum(py_x * a_one_hot, axis=1)
error = K.abs(y - q_value)
quadratic_part = K.clip(error, 0.0, 1.0)
linear_part = error - quadratic_part
loss = K.mean(0.5 * K.square(quadratic_part) + linear_part)
optimizer = RMSprop(lr=0.00025, epsilon=0.01)
updates = optimizer.get_updates(self.model.trainable_weights, [], loss)
train = K.function([self.model.input, a, y], [loss], updates=updates)
return train
# approximate Q function using Convolution Neural Network
# state is input and Q Value of each action is output of network
示例6: optimizer
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def optimizer(self):
a = K.placeholder(shape=(None,), dtype='int32')
y = K.placeholder(shape=(None,), dtype='float32')
py_x = self.model.output
a_one_hot = K.one_hot(a, self.action_size)
q_value = K.sum(py_x * a_one_hot, axis=1)
error = K.abs(y - q_value)
quadratic_part = K.clip(error, 0.0, 1.0)
linear_part = error - quadratic_part
loss = K.mean(0.5 * K.square(quadratic_part) + linear_part)
optimizer = RMSprop(lr=0.00025, epsilon=0.01)
updates = optimizer.get_updates(self.model.trainable_weights, [], loss)
train = K.function([self.model.input, a, y], [loss], updates=updates)
return train
# approximate Q function using Convolution Neural Network
# state is input and Q Value of each action is output of network
示例7: optimizer
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def optimizer(self):
a = K.placeholder(shape=(None, ), dtype='int32')
y = K.placeholder(shape=(None, ), dtype='float32')
py_x = self.model.output
a_one_hot = K.one_hot(a, self.action_size)
q_value = K.sum(py_x * a_one_hot, axis=1)
error = K.abs(y - q_value)
quadratic_part = K.clip(error, 0.0, 1.0)
linear_part = error - quadratic_part
loss = K.mean(0.5 * K.square(quadratic_part) + linear_part)
optimizer = RMSprop(lr=0.00025, epsilon=0.01)
updates = optimizer.get_updates(self.model.trainable_weights, [], loss)
train = K.function([self.model.input, a, y], [loss], updates=updates)
return train
# approximate Q function using Convolution Neural Network
# state is input and Q Value of each action is output of network
# dueling network's Q Value is sum of advantages and state value
示例8: crosschannelnormalization
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def crosschannelnormalization(alpha=1e-4, k=2, beta=0.75, n=5, **kwargs):
"""
This is the function used for cross channel normalization in the original
Alexnet
"""
def f(X):
b, ch, r, c = X.shape
half = n // 2
square = K.square(X)
extra_channels = K.spatial_2d_padding(K.permute_dimensions(square, (0, 2, 3, 1))
, (0, half))
extra_channels = K.permute_dimensions(extra_channels, (0, 3, 1, 2))
scale = k
for i in range(n):
scale += alpha * extra_channels[:, i:i + ch, :, :]
scale = scale ** beta
return X / scale
return Lambda(f, output_shape=lambda input_shape: input_shape, **kwargs)
示例9: crosschannelnormalization
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def crosschannelnormalization(alpha = 1e-4, k=2, beta=0.75, n=5,**kwargs):
"""
This is the function used for cross channel normalization in the original
Alexnet
"""
def f(X):
b, ch, r, c = X.shape
half = n // 2
square = K.square(X)
extra_channels = K.spatial_2d_padding(K.permute_dimensions(square, (0,2,3,1))
, (0,half))
extra_channels = K.permute_dimensions(extra_channels, (0,3,1,2))
scale = k
for i in range(n):
scale += alpha * extra_channels[:,i:i+ch,:,:]
scale = scale ** beta
return X / scale
return Lambda(f, output_shape=lambda input_shape:input_shape,**kwargs)
示例10: smoothing
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def smoothing(im, mode = None):
# utility function to smooth an image
if mode is None:
return im
elif mode == 'L2':
# L2 norm
return im / (np.sqrt(np.mean(np.square(im))) + K.epsilon())
elif mode == 'GaussianBlur':
# Gaussian Blurring with width of 3
return filters.gaussian_filter(im,1/8)
elif mode == 'Decay':
# Decay regularization
decay = 0.98
return decay * im
elif mode == 'Clip_weak':
# Clip weak pixel regularization
percentile = 1
threshold = np.percentile(np.abs(im),percentile)
im[np.where(np.abs(im) < threshold)] = 0
return im
else:
# print error message
print('Unknown smoothing parameter. No smoothing implemented.')
return im
示例11: call
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [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
示例12: get_weightnorm_params_and_grads
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def get_weightnorm_params_and_grads(p, g):
ps = K.get_variable_shape(p)
# construct weight scaler: V_scaler = g/||V||
V_scaler_shape = (ps[-1],) # assumes we're using tensorflow!
V_scaler = K.ones(V_scaler_shape) # init to ones, so effective parameters don't change
# get V parameters = ||V||/g * W
norm_axes = [i for i in range(len(ps) - 1)]
V = p / tf.reshape(V_scaler, [1] * len(norm_axes) + [-1])
# split V_scaler into ||V|| and g parameters
V_norm = tf.sqrt(tf.reduce_sum(tf.square(V), norm_axes))
g_param = V_scaler * V_norm
# get grad in V,g parameters
grad_g = tf.reduce_sum(g * V, norm_axes) / V_norm
grad_V = tf.reshape(V_scaler, [1] * len(norm_axes) + [-1]) * \
(g - tf.reshape(grad_g / V_norm, [1] * len(norm_axes) + [-1]) * V)
return V, V_norm, V_scaler, g_param, grad_g, grad_V
示例13: content_loss
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def content_loss(base, combination):
return K.sum(K.square(combination - base))
示例14: style_loss
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def style_loss(style, combination):
S = gram_matrix(style)
C = gram_matrix(combination)
channels = 3
size = img_height * img_width
return K.sum(K.square(S - C)) / ( 4. * (channels ** 2) * (size ** 2))
示例15: total_variation_loss
# 需要导入模块: from keras import backend [as 别名]
# 或者: from keras.backend import square [as 别名]
def total_variation_loss(x):
a = K.square(
x[:, :img_height-1, :img_width-1, :] -
x[:, 1:, :img_width-1, :])
b = K.square(
x[:, :img_height-1, :img_width-1, :] -
x[:, :img_height-1, 1:, :])
return K.sum(K.pow(a+b, 1.25))