import torch
import numpy as np
import os
import random
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
true_w = [2, -3]
true_b = 4
num_inputs = 2
num_examples = 1000
def get_train_data():
features = torch.from_numpy(np.array(np.random.normal(0.0, 1.0, [num_examples, num_inputs]), dtype=np.float32))
labels = features[:, 0] * true_w[0] + features[:, 1] * true_w[1] + true_b
labels += torch.from_numpy(np.random.normal(0.0, 0.01, labels.shape))
return features, labels
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 = torch.LongTensor(indices[i: min(i + batch_size, _num_examples)]) # 最后⼀次可能不⾜⼀个batch
yield features.index_select(0, j), labels.index_select(0, j)
def linear_reg(X, w, b):
return torch.mm(X, w) + b
def squared_loss(y_hat, y):
return (y_hat - y.view(y_hat.size())) ** 2 / 2
def sgd(params, lr, batch_size):
for param in params:
param.data -= param.grad * lr / batch_size
import torch
import numpy as np
import os
from utils import linear_reg, squared_loss, data_iter, get_train_data, sgd
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
features, labels = get_train_data()
num_inputs = 2
w = torch.tensor([[0], [0]], dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
print(f'w: {w.numpy()}')
w.requires_grad_(True)
b.requires_grad_(True)
batch_size = 10
lr = 0.01
num_epochs = 10
net = linear_reg
loss = squared_loss
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y).sum()
l.backward()
sgd([w, b], lr, batch_size)
w.grad.data.zero_()
b.grad.data.zero_()
print(f'epoch {epoch}')
print(f'loss: {l.item()}')
print(f'w: {w.clone().detach().numpy()}')
print(f'b: {b.clone().detach().numpy()}')