机器学习(五)——缓解过拟合

看图理解过拟合与欠拟合

欠拟合解决方法

  • 增加输入特征项

  • 增加网络参数

  • 减少正则化参数

过拟合解决方法

  • 数据清洗

  • 增大训练集

  • 采用正则化

  • 增大正则化参数

案例

import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
###正则化缓解过拟合
# 正则化在损失函数中引入模型复杂度指标,利用给W加权值,弱化训练数据的噪声(一般不正则化b)

# 正则化的选择
# L1正则化大概率会使很多参数变为0,因此该方法可通过稀疏参数,即加少参数的数量,降低复杂度
# L2正则化会使参数很接近0但不为0,因此该方法可通过减小参数值的大小降低复杂度



###读入数据
df = pd.read_csv("dot.csv")
x_data = np.array(df[['x1', 'x2']])
y_data = np.array(df['y_c'])

##-1的意思是行数自动生成
x_train = np.vstack(x_data).reshape(-1, 2)
y_train = np.vstack(y_data).reshape(-1, 1)

Y_c = [['red' if y else 'blue'] for y in y_train]

##转换数据类型。不然后面矩阵相乘会报错
x_train = tf.cast(x_train, dtype=tf.float32)
y_train = tf.cast(y_train, dtype=tf.float32)

#from_tensor_slices函数切分传入的张量的第一个维度,生成相应的数据集,输入特征与标签一一对应
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)

###这里定义了两层网络
#生成升神经网络参数,输入层为2个神经元(因为两个特征),隐藏层为11个神经元(这个自己选),1层为隐藏层,输出层为1个神经元
#用tf.Variable()保证参数可训练
w1 = tf.Variable(tf.random.normal([2,11]), dtype=tf.float32)
b1 = tf.Variable(tf.constant(0.01, shape=[11]))
##第二层,输出节点必须和标签个数一样所以是1,神经元个数要和前面的保持一致所以是[11,1]
w2 = tf.Variable(tf.random.normal([11,1]), dtype=tf.float32)
b2 = tf.Variable(tf.constant(0.01, shape=[1]))

lr = 0.005#学习率
epoch = 800#循环轮数

#训练部分
for epoch in range(epoch):
    for step, (x_train, y_train) in enumerate(train_db):
        with tf.GradientTape() as tape:
            h1 = tf.matmul(x_train, w1) + b1
            ##relu激活函数
            h1 = tf.nn.relu(h1)
            y = tf.matmul(h1, w2) + b2

            #采用均方误差损失函数mse = mean(sum(y-out)^2)
            loss_mse = tf.reduce_mean(tf.square(y_train - y))

            ###添加l2正则化缓解过拟合#####################################
            loss_regularization = []
            loss_regularization.append(tf.nn.l2_loss(w1))
            loss_regularization.append(tf.nn.l2_loss(w2))
            loss_regularization = tf.reduce_sum(loss_regularization)
            loss = loss_mse + 0.03 * loss_regularization
            #########################################################
        #计算loss对各个参数的梯度
        variables = [w1, b1, w2, b2]
        grads = tape.gradient(loss, variables)
        #开始梯度更新
        #w1 = w1 -lr * w1_grad tape.gradient是自动求导结果与[w1, b1, w2, b2] 索引为0 1 2 3
        w1.assign_sub(lr * grads[0])
        b1.assign_sub(lr * grads[1])
        w2.assign_sub(lr * grads[2])
        b2.assign_sub(lr * grads[3])
    ##每20个epoch 打印一下loss
    if epoch % 20 == 0:
        print('epoch:', epoch, 'loss', float(loss))

##预测部分
print("*******predict********")
xx, yy = np.mgrid[-3:3:.1, -3:3:.1]
# 将xx,yy拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[xx.ravel(), yy.ravel()]
grid = tf.cast(grid, tf.float32)
#将网格坐标放入神经网络,进行预测,probs为输出
probs = []
for x_test in grid:
    #使用训练好的参数w1, b1, w2, b2进行预测
    h1 = tf.matmul([x_test], w1) + b1
    h1 = tf.nn.relu(h1)
    y = tf.matmul(h1, w2) + b2#预测结果
    probs.append(y)
#取第0列给x1,取第1列给x2
x1 = x_data[:, 0]
x2 = x_data[:, 1]
#probs的shape调整成xx的样子
probs = np.array(probs).reshape(xx.shape)
plt.scatter(x1, x2, color = np.squeeze(Y_c))#squeeze去掉维度是1的维度
# 把坐标xx yy和对应的值probs放入contour函数,给probs值0.5的所有点上色
plt.contour(xx, yy, probs, levels=[.5])
plt.show()
#读入红蓝点,画出分隔线,不包含正则化

未正则化的结果(边界不够圆滑)

 

正则化后的结果 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值