tensorflow进阶篇-4(损失函数1)
L2正则损失函数(即欧拉损失函数),L2正则损失函数是预测值与目标函数差值的*方和。L2正则损失函数是非常有用的损失函数,因为它在目标值附*有更好的曲度,并且离目标越*收敛越慢:
# L = (pred - actual)^2 l2_y_vals = tf.square(target - x_vals) l2_y_out = sess.run(l2_y_vals)
L1正则损失函数(即绝对值损失函数)。与L2正则损失函数对差值求*方差不同的是,L1正则损失函数对差值求绝对值。L1正则在目标附*不*滑,这回导致算法不能很好的收敛。
# L = abs(pred - actual) l1_y_vals = tf.abs(target - x_vals) l1_y_out = sess.run(l1_y_vals)
Peseudo-Huber损失函数是Huber损失函数的连续、*滑估计,试图利用L1和L2正则消减极值处的陡峭,使得目标之附*连续。它的表达式依赖与参数delta。
# L = delta^2 * (sqrt(1 + ((pred - actual)/delta)^2) - 1) delta1 = tf.constant(0.25) #delta=0.25的情况下 phuber1_y_vals = tf.multiply(tf.square(delta1), tf.sqrt(1. + tf.square((target - x_vals)/delta1)) - 1.) phuber1_y_out = sess.run(phuber1_y_vals)
delta2 = tf.constant(5.) #delta=5的情况下
phuber2_y_vals = tf.multiply(tf.square(delta2), tf.sqrt(1. + tf.square((target - x_vals)/delta2)) - 1.)
phuber2_y_out = sess.run(phuber2_y_vals)
利用matplotlib绘画出以上的损失函数为:
完整代码:
import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops ops.reset_default_graph() # Create graph sess = tf.Session() #创建与预测函数序列和目标序列作为张量 x_vals = tf.linspace(-1., 1., 500) target = tf.constant(0.) #目标值为0 #L2正则损失函数(即欧拉损失函数) # L = (pred - actual)^2 l2_y_vals = tf.square(target - x_vals) l2_y_out = sess.run(l2_y_vals) #L1正则损失函数(即绝对值损失函数) # L = abs(pred - actual) l1_y_vals = tf.abs(target - x_vals) l1_y_out = sess.run(l1_y_vals) #Peseudo-Huber损失函数是Huber损失函数的连续 *滑估计, #利用L1和L2正则消减极值处的陡峭,使得目标之附*连续。 # L = delta^2 * (sqrt(1 + ((pred - actual)/delta)^2) - 1) delta1 = tf.constant(0.25) #delta=0.25的情况下 phuber1_y_vals = tf.multiply(tf.square(delta1), tf.sqrt(1. + tf.square((target - x_vals)/delta1)) - 1.) phuber1_y_out = sess.run(phuber1_y_vals) delta2 = tf.constant(5.) #delta=5的情况下 phuber2_y_vals = tf.multiply(tf.square(delta2), tf.sqrt(1. + tf.square((target - x_vals)/delta2)) - 1.) phuber2_y_out = sess.run(phuber2_y_vals) # Plot the output: x_array = sess.run(x_vals) plt.plot(x_array, l2_y_out, 'b-', label='L2 Loss') plt.plot(x_array, l1_y_out, 'r--', label='L1 Loss') plt.plot(x_array, phuber1_y_out, 'k-.', label='P-Huber Loss (0.25)') plt.plot(x_array, phuber2_y_out, 'g:', label='P-Huber Loss (5.0)') plt.ylim(-0.2, 0.4) plt.legend(loc='lower right', prop={'size': 11}) plt.show()