思路
- 生成原始数据
- 根据原始数据以及batch_size,生成小批量数据
- 定义模型(网络)
- 定义误差函数
- 定义优化算法
- 主函数传参训练
生成原始数据
def synthetic_data(w, b, num_examples):
""" 生成 y = Xw + b + 噪声。"""
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))
生成小批量数据
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]
定义模型(网络)
def linreg(X, w, b):