1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| import torch import matplotlib.pyplot as plt import random
def generateDataSet(w, b, data_num): x = torch.normal(0, 1, (data_num, len(w))) y = torch.matmul(x, w) + b noise = torch.normal(0, 0.01, y.shape) y += noise return x, y w_true = torch.tensor([8.1, 2, 2, 4]) b_true = torch.tensor(1.1) DataSetNum = 500 X, Y = generateDataSet(w_true, b_true, DataSetNum) plt.scatter(X[:, 3], Y, 1) plt.show()
def getData(data, label, batch_size): length = len(label) indices = list(range(length)) random.shuffle(indices) for each in range(0, length, batch_size): get_indices = indices[each: each + batch_size] get_data = data[get_indices] get_labal = label[get_indices] yield get_data, get_labal
batch_size = 16
def model(x, w, b): y_pred = torch.matmul(x, w) + b return y_pred
def maeloss(y_pred, y): return sum(abs(y_pred - y)) / len(y)
def SGD(params, lr): with torch.no_grad(): for param in params: param -= param.grad * lr param.grad.zero_() lr = 0.03
w = torch.normal(0, 0.01, w_true.shape, requires_grad=True) b = torch.tensor(0.01, requires_grad=True)
epochs = 50 for epoch in range(epochs): data_loss = 0 for x_batch, y_batch in getData(X, Y, batch_size): y_pred = model(x_batch, w, b) loss = maeloss(y_pred, y_batch) loss.backward() SGD([w, b], lr) data_loss += loss print("epoch: %03d, loss: %.6f"%(epoch, data_loss)) print("真实的参数为:", w_true, b_true) print("训练之后的参数:", w, b)
idx = 1 plt.plot(X[:, idx].detach().numpy(), X[:, idx].detach().numpy() * w[idx].detach().numpy() + b.detach().numpy()) plt.scatter(X[:, idx], Y, 1) plt.show()
|