莫烦tensorflow学习记录 (5)什么是过拟合 (Overfitting)

什么是过拟合 (Overfitting)

莫烦讲的非常通俗易懂可以看看https://mofanpy.com/tutorials/machine-learning/tensorflow/intro-overfitting/

我理解就是模型训练的过于敏感,他不能成功的表达除了训练数据以外的其他数据。这就叫做过拟合。

解决方法

方法一:增加数据量,大部分过拟合产生的原因是因为数据量太少。如果我们有成千上万的数据,在整体大量数据影响下,会变得没那么扭曲。

方法二:利用正规化regularization,简化机器学习的关键公式为 y=Wx 。W为机器需要学习到的各种参数。在过拟合中,W 的值往往变化得特别大或特别小。为了不让W变化太大, 我们在计算误差上做些手脚。原始的 cost 误差是这样计算,cost = 预测值-真实值的平方。如果 W 变得太大,我们就让 cost 也跟着变大,变成一种惩罚机制。所以我们把 W 自己考虑进来。

L1正规化,这里 abs 是绝对值。L1:cost=(Wx-real y)^2 + abs(W)

L2 正规化和 L1 类似,只是绝对值换成了平方。L2:cost=(Wx-real y)^2 + (W)^2

其他的L3,L4 也都是换成了立方和4次方等等。形式类似,用这些方法,我们就能保证让学出来的线条不会过于扭曲。

方法三:( dropout)专门用在神经网络的正规化的方法。随机忽略一些神经元,让网络不再完整,这样每次训练的时候就不会过分依赖某些神经元,从而避免过拟合。

Dropout 解决 overfitting

原文章https://mofanpy.com/tutorials/machine-learning/tensorflow/dropout/

TensorFlow提供了强大的dropout方法来解决overfitting问题。

这里的keep_prob是保留概率,即我们要保留的结果所占比例,在run时传入, 当keep_prob=1的时候,相当于100%保留,也就是dropout没有起作用。
sess.run(train_step,feed_dict={xs: X_train, ys: y_train, keep_prob: 1})

 当keep_prob=0.5时候,就是随机消除一般的神经元。

sess.run(train_step,feed_dict={xs: X_train, ys: y_train, keep_prob: 0.5})
# https://mofanpy.com/tutorials/machine-learning/tensorflow/dropout/
import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer

# load data
digits = load_digits()
X = digits.data
y = digits.target
y = LabelBinarizer().fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)

# 为网络输入定义占位符
# 这里的keep_prob是保留概率,即我们要保留的结果所占比例,它作为一个placeholder,
# 在run时传入, 当keep_prob=1的时候,相当于100%保留,也就是dropout没有起作用。
keep_prob = tf.placeholder(tf.float32)
xs = tf.placeholder(tf.float32, [None, 64])  # 8x8
ys = tf.placeholder(tf.float32, [None, 10])

def add_layer(inputs, in_size, out_size, layer_name, activation_function=None): # 定义添加神经层的函数def add_layer(),它有四个参数:输入值、输入的大小、输出的大小和激励函数,我们设定默认的激励函数是None。
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))
    biases = tf.Variable(tf.zeros([1,out_size])+ 0.1)  #机器学习中推荐biases不为0,所以加个0.1
    #定义Wx_plus_b, 即神经网络未激活的值。其中,tf.matmul()是矩阵的乘法。
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    #当activation_function——激励函数为None时,输出就是当前的预测值——Wx_plus_b,不为None时,就把Wx_plus_b传到activation_function()函数中得到输出。
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
        tf.summary.histogram(layer_name + '/outputs', outputs)
    return outputs

# add output layer
l1 = add_layer(xs, 64, 50, 'l1', activation_function=tf.nn.tanh)
prediction = add_layer(l1, 50, 10, 'l2', activation_function=tf.nn.softmax)

# the loss between prediction and real data
# loss函数(即最优化目标函数)选用交叉熵函数。交叉熵用来衡量预测值和真实值的相似程度,如果完全相同,它们的交叉熵等于零。
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))  # loss
tf.summary.scalar('loss', cross_entropy)

# 训练步骤
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#初始化变量
init = tf.global_variables_initializer()

#上面所有的都还没有运行
sess = tf.Session()
merged = tf.summary.merge_all()
# summary writer goes in here
train_writer = tf.summary.FileWriter("logs/train", sess.graph)
test_writer = tf.summary.FileWriter("logs/test", sess.graph)
sess.run(init) #这里运行了init

for i in range(500):
    sess.run(train_step,feed_dict={xs: X_train, ys: y_train, keep_prob: 0.5})
    if i%50==0:
        train_result = sess.run(merged, feed_dict={xs: X_train, ys: y_train, keep_prob: 1})
        test_result = sess.run(merged, feed_dict={xs: X_test, ys: y_test, keep_prob: 1})
        train_writer.add_summary(train_result, i)
        test_writer.add_summary(test_result, i)
原文地址:https://www.cnblogs.com/aimoboshu/p/13811407.html