Tensorflow2.1基础知识---缓解过拟合

  1. 欠拟合和过拟合
    过拟合和欠拟合是导致模型泛化能力不高的两种原因,都是模型学习能力与数据复杂度之间失配的 结果。

    1. 欠拟合:是在模型学习能力较弱,而数据复杂度较高的情况出现,此时模型由于学习能力不足,无 法学习到数据集中的“一般规律”,因而导致泛化能力弱。
    2. 过拟合:是在模型学习能力过强的情况中出现,此时的模型学习能力太强,以至于将训练单个样本 自身的特定都能捕捉到,并将其认为是“一般规律”,因而导致模型泛化能力下降
    3. 各自优缺点
      欠拟合在训练集和测试集上的性能都较差,而过拟合往往能较好地学习训练集数据地性质,而在测试集上地性能较差。
      在这里插入图片描述
  2. 欠拟合和过拟合解决办法

    1. 欠拟合的解决办法:
    	a. 增加输入特征项
    	b. 增减网络
    	c. 减少正则化参数
    2. 过拟合解决办法:
    	a. 数据清洗
    	b. 增大训练集
    	c. 采用正则化
    	d. 增大正则化参数
    
  3. 正则化缓解过拟合
    正则化在损失函数中引入模型复杂度指标,利用给w加权值,弱化了训练数据的噪声(一般不正则化b)
    在这里插入图片描述
    正则化的选择:
    1. L1正则化大概率会使很多参数变为0,因此该方法可通过稀疏参数,即减少参数的数量,降低复杂度
    2. L2正则化会使参数很接近零但不为零,因此该方法可通过减小参数值的大小降低复杂度

  4. 案例:

    	#导入所需模块
    	import tensorflow as tf
    	from matplotlib import pyplot as plt
    	import numpy as np
    	import pandas as pd
    	
    	#读入数据/标签 生成x_train y_train
    	df = pd.read_csv('dot.csv')
    	x_data = np.array(df[['x1','x2']])
    	y_data = np.array(df['y_c'])
    	
    	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的数据类型,否则后面矩阵相乘时会因数据类型问题报错
    	x_train = tf.cast(x_train,tf.float32)
    	y_train = tf.cast(y_train,tf.float32)
    	
    	#from_tensor_slices函数切分传入张量的第一个维度,生成相应的数据集,使输入特征和标签值一一对应
    	train_db = tf.data.Dataset.from_tensor_slices((x_train,y_train)).batch(32)
    	
    	#生成神经网络参数,输入层为两个神经单元,隐藏层为11个神经元,1层隐藏层,输出层为1个神经元
    	w1 = tf.Variable(tf.random.normal([2,11]),dtype=tf.float32)
    	b1 = tf.Variable(tf.constant(0.01, shape=[11]))
    	w2 = tf.Variable(tf.random.normal([11,1]),dtype=tf.float32)
    	b2 = tf.Variable(tf.constant(0.01, shape=[1]))
    	
    	lr = 0.01 #学习率
    	epoch = 400 #循环次数
    	
    	#训练部分
    	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  #记录神经网络乘加运算
    	            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 = []
    	            #tf.nn.l2_loss(w) = sum(w ** 2) / 2
    	            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  #REGULARIZER = 0.03
    	        #计算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在 -3到3之间步长为0.01,yy在-3到3之间步长0.01,生成间隔数值点
    	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:
    	    #使用训练好的参数进行预测
    	    h1 = tf.matmul([x_test],w1) + b1
    	    h1 = tf.nn.relu(h1)
    	    y = tf.matmul(h1,w2) + b2 #y为预测结果
    	    probs.append(y)
    	
    	#取第0列给x1,取第一列给x2
    	x1 = x_data[:,0]
    	x2 = x_data[:,1]
    	#probs的shape调整成xx的样子
    	probs = np.array(probs).reshape(xx.shape)
    	#画坐标为x1,x2的散点图,颜色为color   squeeze去掉维度是1的维度,相当于[['red'],['blue']],内层括号变为['red','blue']
    	plt.scatter(x1,x2,color = np.squeeze(Y_c))
    	#把坐标xx yy和对应的值probs放入contour函数,给probs值为0.5的所有点上色  plt点show后 显示的是红蓝点的分界线
    	plt.contour(xx,yy,probs,levels=[.5])
    	plt.show()
    
    
  5. 正则化和没有正则化的效果对比
    在这里插入图片描述

下面的是笔者的微信公众号,欢迎关注,会持续更新c++、python、tensorflow、机器学习、深度学习等系列文章

                    在这里插入图片描述

发布了38 篇原创文章 · 获赞 49 · 访问量 6935

猜你喜欢

转载自blog.csdn.net/Xiao_Jie123/article/details/104966893