torch

[-0.974375, -0.050625, -0.02375]                 6.774689
[-0.97625, -0.050625, -0.02375]                  6.765250
[-0.963125, -0.050625, -0.02375]                 6.761868
[-0.974375, -0.0507421875, -0.0236914063]        6.761267
[-0.973671875, -0.050859375, -0.023984375]       6.752429
[-0.9744921875, -0.0507421875, -0.0236914063]    6.751828
[-0.981875, -0.054375, -0.02375]                 6.751656
[-0.978125, -0.054375, -0.02375]                 6.738835
[-0.978125, -0.0525, -0.02375]                   6.738234
[-0.9753125, -0.0515625, -0.02421875]            6.697738


import torch
import matplotlib.pyplot as plt
import os
from pandas import Series
# https://blog.youkuaiyun.com/weixin_43821559/article/details/123296140
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# 数据集
x_data = torch.tensor([
    [1.0, 2.0, 3.0],
    [2.0, 3.0, 4.0],
    [2.0, 1.0, 4.0],
    [2.0, 3.0, 2.0],])
y_data = [[1., 4., 9.],
          [2., 6., 12.]]
# 权重参数初始值均为1
w = torch.tensor([1.0, 1.0, 1.0])
w.requires_grad = True  # 需要计算梯度

y = x_data * w
a = (y.sum(axis=1)).tolist()

ser = Series(a)
ser = ser.sort_values(ascending=False)
print(ser.index.tolist())
raise Exception(111)


# 前向传播
def forward(x):
    return x * w


# 计算损失
def loss(x, y):
    y_pred = forward(x)
    y_pred = y_pred.sum(axis=1).tolist()
    a = (y_pred.sum(axis=1)).tolist()
    ser = Series(a)
    ser = ser.sort_values(ascending=False)
    ser.index.tolist()
    return (y_pred - y) ** 2


# 训练模块
print('predict (before tranining) ', 4, forward(4).item())
epoch_list = []
w_list = []
loss_list = []
for epoch in range(1000):
    for x, y in zip(x_data, y_data):
        l = loss(x, y)
        l.backward()  # 后向传播
        print('\tgrad: ', x, y, w.grad.data)
        w.data = w.data - 0.01 * w.grad.data  # 梯度下降

        w.grad.data.zero_()  # 梯度清零操作

    print('progress: ', epoch, l.item())
    epoch_list.append(epoch)
    w_list.append(w.data)
    loss_list.append(l.item())
print('predict (after tranining) ', 4, forward(4).item())

# 绘图
plt.plot(epoch_list, loss_list, 'b')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.grid()
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值