一元方程y=theta*x,通过梯度下降求theta
如果有常数项怎么办?
如:y=theta*x + b
下个博客进行学习。
数据集根据y = 3x构造,并加一定的随机数构造出数据集
import numpy as np
import matplotlib.pyplot as plt
LEN = 50
X = np.arange(0, LEN) # 生成0,1,2...LEN-1整数
# rand从-5到+5
np.random.seed(1)
rand = (np.random.random(LEN) * 2 - 1) * 5
Y = X * 3 + rand
# X、Y分布如下图所示
plt.scatter(X, Y)
#plt.show() # 展示散点图
# X、Y 连接
X = X.reshape(LEN, 1)
Y = Y.reshape(LEN, 1)
allData = np.concatenate((X, Y), axis = 1)
划分训练集、测试集
# 随机打乱数据集
np.random.shuffle(allData)
# 划分训练集、测试集
ratio = 0.8
index = (int)(allData.shape[0] * ratio)
trainData = allData[:index] # 训练集数据
testData = allData[index:] # 测试集数据
超参数设置
# 超参数设置
# 学习率
lr = 0.0005
# 训练集大小(每个batch随机梯度下降迭代次数)
N = trainData.shape[0]
# 误差大小
epsilon = 200
模型训练
# 待估及参数(theta)
theta = np.random.rand() # 随机初始化一个值
# 迭代次数标识
iter = 1
# 参数记录列表,包括loss、迭代次数以及theta
loss_list = []
iter_list = []
theta_list = []
loss = np.inf
while True:
# 打乱训练集顺序
np.random.shuffle(trainData)
for i in range(N):
# 随机样本
x = trainData[i, 0]
y = trainData[i, 1]
# 计算梯度
grad = (theta * x - y) * x
# 更新参数
theta = theta - lr * grad
#print("x: %.2f\t\t y:%.2f\t\t\tgrad: %.4f\t\t\ttheta: %.4f" % (x, y, grad, theta))
# 一个batch结束后,对所有测试样本进行loss求和
print("current theta:%.3f" % theta)
loss = np.sum(0.5 * (trainData[:, 0] * theta - trainData[:, 1]) ** 2) # ( (y_predict - y_true)^2 ) /2
theta_list.append(theta)
loss_list.append(loss)
iter_list.append(iter)
print("No.%d:\t grad = %f\t theta: %f\tloss: %f" %(iter, grad, theta, loss))
iter += 1
# 达到允许的误差,结束训练
if loss < epsilon:
print("Traing Completed!")
break
训练结果
结果展示
注:SGD算法实现流程
参考:
https://blog.csdn.net/xingzhe123456789000/article/details/107206321