%matplotlib inline
import matplotlib.pyplot as plt
import random
import torch
'''生成数据集'''defsynthetic_data(w,b,num_examples):'''生成y=Xw+b+噪声'''
X = torch.normal(0,1,(num_examples,len(w)))#normal函数的第三个参数是形状
y = torch.matmul(X,w)+ b
y += torch.normal(0,0.01, y.shape)return X,y.reshape((-1,1))
true_w = torch.tensor([2,-3.4])
true_b =4.2
features,labels=synthetic_data(true_w,true_b,1000)
'''读取小批量数据集''''''读取方法:假设有n个样本,先生成一个长度为n的列表(其元素的作用类似下标),然后把它打乱,然后去批量大小
的下标数(这时是按顺序取的),然后取这些下标对应的样本'''defdata_iter(batch_size,features,labels):'''batch_size为批量大小'''
num_examples =len(features)
indices =list(range(num_examples))#一个list#range返回一个可迭代对象,而不是列表类型,只有一个参数时默认从0开始计数到那个参数为止,但是不会包括那个参数#range若有三个参数,那么第一个表示开始,第二个表示结束,第三个表示步长#样本随机读取,没有顺序
random.shuffle(indices)#shuffle函数是将列表所有元素随机排序for i inrange(0,num_examples,batch_size):
batch_indices = torch.tensor(indices[i:min(i + batch_size,num_examples)])yield features[batch_indices],labels[batch_indices]
batch_size=10for X,y in data_iter(batch_size,features,labels):print(X,'\n',y)break
'''初始化模型参数''''''通过从均值为0,标准差为0,01的正态分布中采样随机数来初始化权重,并将偏置初始化为0''''''requires_grad用于说明当前量是否需要在计算中保留对应的梯度信息,若为True,则反向传播时tensor会自动求导'''
w = torch.normal(0,0.01,size =(2,1),requires_grad=True)
b = torch.zeros(1,requires_grad=True)
'''定义模型'''deflinreg(X,w,b):'''线性回归模型'''return torch.matmul(X,w)+ b