**使用带有噪声的线性模型构造数据集,并根据有限的数据恢复该线性模型的参数。**其中包括数据集构造、模型参数初始化、损失函数定义、定义优化算法和训练等过程。是大多数算法实现过程的一个缩影,理解此过程有助于在开发或改进算法时更深刻了解其算法的构造和框架。
过程详解
生成数据
此时以简单的线性模型为例,生成1000个2维的数据,作为样本集。每个样本都符合均值为0,标准差为1的正态分布。具体代码如下所示。
import torch
def synthetic_data(w,b,num_examples):
"""生成y=Wx+b+噪声"""
##X是一个1000行2列的数据,符合0,1的正态分布
X=torch.normal(0,1,(num_examples,len(w)))#特征
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)
print()
print('features',features[0],'\nlabels:',labels[0])
print('features.shape',features.shape,'\nlabels.shape:',labels.shape)
输出:
features tensor([0.1724, 0.8911])
labels: tensor([1.5308])
features.shape torch.Size([1000, 2])
labels.shape: torch.Size([1000, 1])
可以看出,已经生成了1000个2维的样本集X,大小为1000行2列。添加完噪声的标签labels,为1000行1列,即一个样本对应一个标签。
对生成数据的第一维和标签的结果可视化:
import matplotlib.pyplot as plt
plt.scatter(features[:,0].detach().numpy(),labels.detach().numpy(),1)
plt.savefig('x1000.jpg')
plt.show()
小批量划分数据集
把生成的数据打乱,并根据设置的批量大小,根据索引提取样本和标签。
def data_iter(batch_size,features,labels):
num_examples=len(features)
indices=list(range(num_examples))
##这些样本是随机读取的,没有特定顺序
random.shuffle(indices)
for i in range(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=10#批量设置为10
for X,y in data_iter(batch_size,features,labels):
print(X,'\n',y)