#找一条线尽可能多的你和数据点 目的是求回归方程中的权重项和偏置项
#偏置项:将结果做一个微调
#f(x)=C1X1+C2X2+ C3 就是要求c1 c2 c3
#数据预处理中添加一个全1列
#数据之间是相互独立的 数据尽可能来自相同的分布
#高斯分布 在均值附近浮动的数据占大多数
#偏置项和误差项区别 偏置项决定平面上下平移 误差项是因为每组数据不可能和平面完全重合
import matplotlib
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
def setdata(w,b,n):
x=torch.normal(0,1,(n,len(w)))
print(f'x的大小形状{x.shape}')
y=torch.matmul(x,w)+b
print(f'y的大小形状{y.shape}')
y+=torch.normal(0,0.001,y.shape)
return x,y.reshape(-1,1)
truew=torch.tensor([2,-3.4])#两行一列的列表
trueb=-4.2
feature,label=setdata(truew,trueb,1000)
print(feature.shape)#输入数据
print(len(feature))
print(label.shape)#输入数据经过刚刚线性运算得到的数据 作为标签
plt.plot(feature[:,0],feature[:,1],'.')
plt.show()
def dataread(batch_size,features,lables):
num_e=len(features)
print(f'当前num——e列表的总长度为{num_e}')
indices=list(range(num_e))#这个函数不太理解 生成一个列表 里面的数字是从0到num_e-1
random.shuffle(indices)#将上面的结果随机化 也就是列表中的数字不再有序
for i in range(0,num_e,batch_size):
batch_indices=torch.tensor(
indices[i:min(i+batch_size,num_e)]
)
yield features[batch_indices], lables[batch_indices]
#每次产生一个随机的标号
#return在函数中返回某个值,返回后彻底退出函数不再执行
#yield 函数返回值后不会退出函数,会在返回函数值之后接着返回的地方开始执行
#这样就可以返回很多的序列
batch_size=10
for x,y in dataread(batch_size,feature,label):
print(x,'\n',y)
break
#给要求的参数进行初始化
w=torch.normal(0,0.01,size=(2,1),requires_grad=True)
print(f'w的初始值是{w}')
b=torch.zeros(1,requires_grad=True)
print(f'b的初始值是{b}')
#定义模型
def line(x,w,b):
return torch.matmul(x,w)+b
#定义损失函数
def loss(y_hat,y):
return(y_hat-y.view(y_hat.size()))**2/2
#定义优化算法
def better(list,lr,batch_size):
for i in list:
i.data-= lr * i.grad / batch_size#
print(f'i.data是什么{i.data}')
#下面开始模型训练
lr=0.03
num_epochs=10
#net=line()带括好相当于是要得到返回执行的结果
#loss=loss()
net=line#可以理解为得到的是整个函数体,相当于给函数一个别名
loss=loss
for epoch in range(num_epochs):
for x,y in dataread(batch_size,feature,label):
l=loss(net(x,w,b),y)
l.sum().backward()#在这个位置更新w和b的权值 反向传播 对损失函数求导 确定梯度下降的方向 梯度下降是对损失函数进行处理的
#backward计算了梯度下降的方向和大小,用优化函数better来修改对应的参数的值
better([w,b],lr,batch_size)#利用更新后的w和b的值计算新的梯度
w.grad.data.zero_()
b.grad.data.zero_()
print(f'w的值更新后值是{w}')
print(f'b的更新后值是{b}')
train_l=loss(net(feature,w,b),label)#计算当前更新好的w和b损失率
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
print(truew)
print(trueb)
print(w)
print(b)
初学机器学习——线性回归代码实现
最新推荐文章于 2024-04-10 19:04:43 发布