首先我们先了解一下基本要素
1,模型
2,模型训练
3,训练数据
4,损失函数
5,优化算法(好好学最优化方法)
6,模型预测
首先线性回归的从零开始
first,生成数据集,函数原型为 y_hat = x1 * w1 + x2 * w2 + b
# 生成数据集
# y_hat = x1 * w1 + x2 * w2 + b
num_input = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = nd.normal(scale = 1, shape = (num_examples, num_input))
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += nd.normal(scale = 0.01, shape = labels.shape)
second,读取数据集
# 读取数据集
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):
j = nd.array(indices[i: min(i + batch_size, num_examples)]) #随机取样
yield features.take(j), labels.take(j)
third,初始化模型参数
w = nd.normal(scale = 0.01, shape = (num_input, 1))
b = nd.zeros(shape = (1, 1))
next,定义模型
def linreg(X, w, b):
return nd.dot(X, w) + b
next,定义损失函数 l = (y_hat - y) ^ 2 * 0.5
# 定义损失函数 l = (y_hat - y) ^ 2 * 0.5
def squared_loss(y_hat, y):
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
next,定义优化算法 迭代算法,其中params是超参数,lr是学习率,batch_size是批量大小
def sgd(params, lr, batch_size):
for param in params:
param[:] = param - lr * param.grad / batch_size
finally, 训练模型
lr = 0.03
num_epochs = 3
for epoch in range(num_epochs): # 一共迭代num_epochs个迭代周期
for X, y in data_iter(batch_size, features, labels):
with autograd.record():
l = squared_loss(linreg(nd.array(X), w, b), y)
l.backward()
sgd([w, b], lr, batch_size)
train_l = squared_loss(linreg(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().asnumpy()))
print(true_w, w)
print(true_b, b)
博客介绍了模型训练的基本要素,包括模型、训练数据、损失函数等。重点阐述了线性回归从零开始的实现步骤,如生成数据集、读取数据、初始化参数、定义模型、损失函数和优化算法,最后完成模型训练。


被折叠的 条评论
为什么被折叠?



