(1)编码实现基于梯度下降的单变量和多变量线性回归算法,包括梯度的计算与验证;

(2)画数据散点图和求得的直线;

(3)画梯度下降过程中损失的变化图;

(4)基于训练得到的参数,输入新的样本数据,输出预测值;

上面是代码的格式,由于在python中格式是非常重要的,如果格式错了很可能导致运行出错,读取的文件是做实验老师给的文件。

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('data.csv', delimiter=',', dtype='int', skiprows=1)#读取TXT文件,分隔符为‘,’,skiprows=1跳过第一行
train_x = train[:,0]#训练全部行,第0列
train_y = train[:,1]#训练全部行,第1列
train_x
type(train_x)
train_x.shape#可以获取矩阵的形状,获取的结果是一个元组



# 绘图
plt.plot(train_x,train_y,'o')#.plot(x,y,ls,lw,lable)//x,y数轴上的数值,ls:折线图的风格lw:标记内容的标签文本
plt.show()


# 参数初始化
theta0 = np.random.rand()
theta1 = np.random.rand()

# 预测函数
def f(x):
    return theta0 + theta1 * x

# 目标函数
def E(x, y):
    return 0.5 * np.sum((y - f(x)) ** 2)



# 标准化
mu = train_x.mean()#.mean()求平均值
sigma = train_x.std()#计算标准差
def standardize(x):
    return (x - mu) / sigma

train_z = standardize(train_x)

# 绘图
plt.plot(train_z,train_y,'o')
plt.show()

# 学习率
ETA = 1e-3

# 误差的差值
diff = 1

# 更新次数
count = 0


# 直到误差的差值小于 0.01 为止,重复参数更新
error = E(train_z, train_y)

while diff > 1e-2:
    # 更新结果保存到临时变量
    tmp_theta0 = theta0 - ETA * np.sum((f(train_z) - train_y))
    tmp_theta1 = theta1 - ETA * np.sum((f(train_z) - train_y) * train_z)

    # 更新参数
    theta0 = tmp_theta0
    theta1 = tmp_theta1

    # 计算与上一次误差的差值
    current_error = E(train_z, train_y)
    diff = error - current_error
    error = current_error

    # 输出日志
    count += 1
    log = '第 {} 次 : theta0 = {:.3f}, theta1 = {:.3f}, 差值 = {:.4f}'
    print(log.format(count, theta0, theta1, diff))

# 绘图确认
x = np.linspace(-3, 3, 100)
plt.plot(train_z, train_y, 'o')
plt.plot(x, f(x))
plt.show()

f(standardize(100))//预测值


Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐