0
点赞
收藏
分享

微信扫一扫

基于python+vue超市货品信息管理系统flask-django-php-nodejs

Gaaidou 03-24 11:00 阅读 2

介绍:

 手动生成数据集:

%matplotlib inline
import torch
from d2l import torch as d2l
import random

#"""生成y=Xw+b+噪声"""
def synthetic_data(w, b, num_examples):  #生成num_examples个样本
    X = d2l.normal(0, 1, (num_examples, len(w)))#随机x,长度为特征个数,权重个数
    y = d2l.matmul(X, w) + b#y的函数
    y += d2l.normal(0, 0.01, y.shape)#加上0~0.001的随机噪音
    return X, d2l.reshape(y, (-1, 1))#返回

true_w = d2l.tensor([2, -3.4])#初始化真实w
true_b = 4.2#初始化真实b

features, labels = synthetic_data(true_w, true_b, 1000)#随机一些数据
print(features)
print(labels)

显示数据集:

print('features:', features[0],'\nlabel:', labels[0])

'''
features: tensor([ 2.1714, -0.6891]) 
label: tensor([10.8673])
'''

d2l.set_figsize()
d2l.plt.scatter(d2l.numpy(features[:, 1]), d2l.numpy(labels), 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_size
        batch_indices = d2l.tensor(
            indices[i: min(i + batch_size, num_examples)])
        yield features[batch_indices], labels[batch_indices]
        

定义模型:

#定义模型
def linreg(X, w, b):  
    """线性回归模型"""
    return d2l.matmul(X, w) + b

定义损失函数:

#定义损失和函数
def squared_loss(y_hat, y):  #@save
    """均方损失"""
    return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2

定义优化算法(小批量随机梯度下降):

#定义优化算法  """小批量随机梯度下降"""
def sgd(params, lr, batch_size):  #参数、lr学习率、
    with torch.no_grad():
        for param in params:
            param -= lr * param.grad / batch_size
            param.grad.zero_()

模型训练:

#训练
lr = 0.03#学习率
num_epochs = 3#数据扫三遍
net = linreg#模型
loss = squared_loss#损失函数
#初始化模型参数
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)#权重
b = torch.zeros(1, requires_grad=True)#b全赋为0


for epoch in range(num_epochs):
    for X, y in data_iter(batch_size, features, labels):#拿出一批量x,y
        l = loss(net(X, w, b), y)  # X和y的小批量损失,实际的和预测的
        
        # 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
        # 并以此计算关于[w,b]的梯度
        l.sum().backward()
        sgd([w, b], lr, batch_size)  # 使用参数的梯度更新参数
        
    with torch.no_grad():
        train_l = loss(net(features, w, b), labels)
        print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
'''
epoch 1, loss 0.037302
epoch 2, loss 0.000140
epoch 3, loss 0.000048
'''


print(f'w的估计误差: {true_w - d2l.reshape(w, true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
'''
w的估计误差: tensor([0.0006, 0.0001], grad_fn=<SubBackward0>)
b的估计误差: tensor([-0.0003], grad_fn=<RsubBackward1>)
'''

print(w)
'''
tensor([[ 1.9994],
        [-3.4001]], requires_grad=True)
'''

print(b)
'''
tensor([4.2003], requires_grad=True)
'''
举报

相关推荐

0 条评论