数据挖掘与机器学习 线性回归设计 实训1
(1)实训目的
1.掌握回归的基本思想;
2.掌握梯度法的基本原理 。
(2)主要内容
1.实现一元线性回归;
2.画出散点图、回归参数与迭代次数的变化曲线;
3.分析不同数据变化对回归结果的影响。
(3)具体处理步骤
1. 导入数据集,绘制数据的散点图
data1.txt 数据集下载
1 2 3 4 5 6 7 8 9
| import numpy as np import matplotlib.pyplot as plt
data=np.loadtxt("data1.txt", delimiter=",")
x=data[:,0:1] y=data[:,1:] plt.scatter(x,y) plt.show()
|

(97, 2)
2. 对特征进行归一化处理
1 2 3 4 5
| def featureNormalize(x): avg = x.mean() sstd = np.std(x, axis=0, ddof=1) x = (x-avg)/sstd return x, avg, sstd
|
3.1 定义损失函数 h_theta是预测函数(假设函数),j_theta是损失函数
1 2 3
| def computeCost(x, y, theta): m = x.shape[0] return np.sum((np.dot(x,theta) - y)**2)/(2*m)
|
3.2 梯度下降算法
利用公式 theta : 是预测函数每项的系数,times:梯度下降次数,alpha:梯度下降参数变化率
1 2 3 4 5 6 7 8 9 10 11
| def gradientDescent(x, y, theta, times, alpha): theta_0 = np.ones(x.shape[0]).T x = np.insert(x, 0, theta_0, axis=1) m = x.shape[0] n = x.shape[1] costs = np.zeros(times) for num in range(times): for j in range(n): theta[j] = theta[j] + (alpha/m) * np.sum(y - np.dot(x,theta) * x[:,j].reshape(-1,1)) costs[num] = computeCost(x, y, theta) return costs
|
4. 计算求得的直线
1 2 3 4 5 6 7 8 9 10 11 12 13
| x_orgin=x y_orgin=y
x1, avg, sstd = featureNormalize(x_orgin)
theta = np.zeros(x1.shape[1]+1).reshape(-1,1) times = 600 alpha = 0.01 costs = gradientDescent(x1, y_orgin, theta, times, alpha)
plt.scatter(x1, y_orgin) h_theta = theta[0]+theta[1]*x1 plt.plot(x1, h_theta, color= 'red')
|

1 2 3 4
| print('预测函数: y = %f + %f * x' % (theta[0], theta[1]))
print('x=3, y = %f' % (theta[0] + 3*theta[1]))
|
预测函数: y = 5.825092 + 5.884855 * x
x=3, y = 23.479657
5. 画损失函数,损失随迭代次数变化的曲线
1 2
| x_times = np.linspace(1,times,times) plt.plot(x_times, costs[0:times], color="orange",linewidth=3)
|

6. 结果分析
分析可知,当迭代次数到200次左右时,损失函数趋于收敛损失值达到最小值,迭代次数太多,可能使得出现过拟合现象
alpha 越小时,即步长越小,使得训练过程中的变化速度较慢,但可能更易于损失函数收敛
(4)参考资料
data1.txt 数据集下载
机器学习讲解-B站
使用梯度下降法求解线性回归问题
Python机器学习笔记 - AcWing