机器学习与数据挖掘-实验一

(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))//预测值


  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值