梯度下降例子(代码记录)(01)

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()}')

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值