L1正则化就是两套数据相减,就绝对值,再求平均
这里两套数据相减,求绝对值,高斯滤波,再求平均
import tensorflow as tf
import numpy as np
import torch
#模仿matlab的fspecial函数,创建滤波算子(计算SSIM用)
def _tf_fspecial_gauss(size, sigma, channels=1):
"""Function to mimic the 'fspecial' gaussian MATLAB function
"""
x_data, y_data = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]
x_data = np.expand_dims(x_data, axis=-1)
x_data = np.expand_dims(x_data, axis=-1)
y_data = np.expand_dims(y_data, axis=-1)
y_data = np.expand_dims(y_data, axis=-1)
x = tf.constant(x_data, dtype=tf.float32)
y = tf.constant(y_data, dtype=tf.float32)
g = tf.exp(-((x**2 + y**2)/(2.0*sigma**2)))
window = g / tf.reduce_sum(g)
return tf.tile(window, (1,1,channels,channels))
#高斯卷积
def tf_gauss_conv(img, filter_size=11, filter_sigma=1.5):
_, height, width, ch = img.get_shape().as_list()
size = min(filter_size, height, width)
sigma = size * filter_sigma / filter_size if filter_size else 0
window = _tf_fspecial_gauss(size, sigma, ch) # window shape [size, size]
padded_img = tf.pad(img, [[0, 0], [size//2, size//2], [size//2, size//2], [0, 0]], mode="CONSTANT")
return tf.nn.conv2d(padded_img, window, strides=[1,1,1,1], padding='VALID')
#高斯加权的L1正则化
def tf_gauss_weighted_l1(img1, img2, mean_metric=True, filter_size=11, filter_sigma=1.5):
diff = tf.abs(img1 - img2)
L1 = tf_gauss_conv(diff, filter_size=filter_size, filter_sigma=filter_sigma)
if mean_metric:
return tf.reduce_mean(L1)
else:
return L1
#%%
img1 = np.arange(10000,dtype=np.float32).reshape([1,100,100,1])
img2 = np.arange(10000,dtype=np.float32).reshape([1,100,100,1])-1
gauss_weighted_l1 = tf_gauss_weighted_l1(tf.constant(img1),tf.constant(img2))
with tf.Session() as sess:
print(sess.run(gauss_weighted_l1))