用Numpy实现线性回归
一、理论推导
二、代码实现
引入numpy包和random包
import random
import numpy as np
主要函数如下
1.构造数据集
def synthetic_data(w,b,num_examples):
#生成y=Xw+b+噪声 (加噪声是为了验证是否可以拟合) w=[2,-3.4],b=4.2
X=np.random.normal(0, 1, (num_examples,len(w)))
y=np.matmul(X,w)+b
y+=np.random.normal(0,0.01,y.shape) #取噪声偏置
return X,y.reshape((-1,1))
2.构造迭代器
def data_iter(bath_size,features,labels):
num_examples=len(features)
indices=list(range(num_examples))
#设置shuffle
random.shuffle(indices)
for i in range(0,num_examples,bath_size):
bath_indices=np.array(indices[i:min(i+bath_size,num_examples)])
yield features[bath_indices],labels[bath_indices]
3.定义模型
def Linreg(X,w,b):
return np.matmul(X,w)+b[0]
4.定义损失函数
def squared_loss(y_hat,y,batch_size):
#均方损失
return ((y_hat-y)**