day-17 L1和L2正则化的tensorflow示例

机器学习中几乎都可以看到损失函数后面会添加一个额外项,常用的额外项一般有两种,一般英文称作ℓ2-norm,中文称作L1正则化L2正则化,或者L1范数L2范数。L2范数也被称为权重衰减(weight decay)。

一般回归分析中回归w表示特征的系数,从上式可以看到正则化项是对系数做了处理(限制)。L1正则化和L2正则化的说明如下:

  • L1正则化是指权值向量||w||1
  • L2正则化是指权值向量2

关于二者如何解决机器学习中过拟合问题,可以参考如下链接:

https://blog.csdn.net/weiyongle1996/article/details/78161512

https://blog.csdn.net/jinping_shi/article/details/52433975

tensorflow中提供了两个函数,用于求某个权重w矩阵的L1和L2正则化,下面是代码示例:

'''
输入:
x = [[1.0,2.0]]
w = [[1.0,2.0],[3,0,4.0]]

输出:
y = x*w = [[7.0,10.0]]
l1 = (1.0+2.0+3.0+4.0)*0.5 = 5.0
l2 = (1.0**2 + 2.0**2 + 3.0**2 + 4.0**2) / 2)*0.5 = 7.5
'''

import tensorflow as tf
from tensorflow.contrib.layers import *

w = tf.constant([[1.0,2.0],[3.0,4.0]])
x = tf.placeholder(dtype=tf.float32,shape=[None,2])
y = tf.matmul(x,w)

with tf.Session()  as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    print(sess.run(y,feed_dict={x:[[1.0,2.0]]}))
    print("=========================")
    print(sess.run(l1_regularizer(scale=0.5)(w)))
    #(1.0+2.0+3.0+4.0)*0.5 = 5.0
    print("=========================")
    print(sess.run(l2_regularizer(scale=0.5)(w)))
    #(1.0**2 + 2.0**2 + 3.0**2 + 4.0**2) / 2)*0.5 = 7.5