神经网络实现torch温度计问题

import torch
from matplotlib import pyplot as plt
import torch.optim as optim
import torch.nn as nn
from collections import OrderedDict
#torch.unsqueeze()这个函数主要是对数据维度进行扩充。参数为0数据为行方向扩,为1列方向扩,再大错误
# 为什么用unsqueeze
# 因为PyTorch的nn.Linear()是用于设置网络中的全连接层的,
# 需要注意的是全连接层的输入与输出都是二维张量,一般形状为[batch_size, size]

t_c = [0.5,  14.0, 15.0, 28.0, 11.0,  8.0,  3.0, -4.0,  6.0, 13.0, 21.0]
t_u = [35.7, 55.9, 58.2, 81.9, 56.3, 48.9, 33.9, 21.8, 48.4, 60.4, 68.4]
t_c = torch.tensor(t_c).unsqueeze(1) # <1>
t_u = torch.tensor(t_u).unsqueeze(1) # <1>
n_samples = t_u.shape[0]
n_val = int(0.2 * n_samples)
shuffled_indices = torch.randperm(n_samples)
#np.random.permutation() :随机排列一个序列
#[:x]:选取数组前x个
#[x:]:选区数组前2个后的
#加负号时为将[:x]或[x:]数组中元素去除了之后的数组
train_indices = shuffled_indices[:-n_val]
val_indices = shuffled_indices[-n_val:]
# print(n_samples)
# print(n_val)
# print(shuffled_indices)
# print(train_indices,shuffled_indices[:n_val])
# print(val_indices,shuffled_indices[n_val:])
t_u_train = t_u[train_indices]
t_c_train = t_c[train_indices]
t_u_val= t_u[val_indices]
t_c_val = t_c[val_indices]
t_un_train=0.1*t_u_train
t_un_val=0.1*t_u_val
# t_c_train = t_c_train/21.0
# t_c_val = t_c_val/21.0
# t_un_train=t_u_train/68.4
# t_un_val=t_u_val/68.4
def training_loop(n_epochs, optimizer, model, loss_fn,
                  t_u_train, t_u_val, t_c_train, t_c_val):
    for epoch in range(1, n_epochs + 1):
        # 训练集的前向
        t_p_train = model(t_un_train)
        loss_train = loss_fn(t_p_train, t_c_train)
        #验证集的前向
        t_p_val = model(t_un_val)
        loss_val = loss_fn(t_p_val, t_c_val)

        optimizer.zero_grad()
        loss_train.backward()
        optimizer.step()

        if epoch == 1 or epoch % 1000 == 0:
            print('Epoch %d, Training loss %.4f, Validation loss %.4f' % (
                    epoch, float(loss_train), float(loss_val)))
# linear_model = nn.Linear(1, 1)
seq_model = nn.Sequential(OrderedDict([
        ('hidden_linear', nn.Linear(1, 8)),
        ('hidden_activation', nn.Tanh()),
        ('output_linear', nn.Linear(8, 1))
    ]))
#该模型将1个输入特征散开为8个隐藏特征,然后将通过tanh激活函数,
# 最后将得到的8个数字线性组合为1个输出特征
#隐藏特征个数和过拟合成正比

optimizer = optim.SGD(seq_model.parameters(), lr=1e-3) # 为了稳定性调小了梯度
#optimizer = optim.SGD(linear_model.parameters(), lr=1e-2)
#optimizer = optim.SGD([params], lr=learning_rate)
#注意直接通过模型实例获取参数,无需自己创建参数

training_loop(
    n_epochs = 3000,
    optimizer = optimizer,
    model = seq_model,
    loss_fn = nn.MSELoss(), # 不再使用自己定义的loss
    t_u_train = t_un_train,
    t_u_val = t_un_val,
    t_c_train = t_c_train,
    t_c_val = t_c_val)

# print('output', seq_model(t_un_val))
# print('answer', t_c_val)
# print('hidden', seq_model.hidden_linear.weight.grad)
t_range = torch.arange(20., 90.).unsqueeze(1)
print(t_range)
fig = plt.figure(dpi=100)
plt.xlabel("Fahrenheit")
plt.ylabel("Celsius")
plt.plot(t_u.numpy(), t_c.numpy(), 'o')
plt.plot(t_range.numpy(), seq_model(0.1 * t_range).detach().numpy(), 'c-')
#此时在画函数sign的图像
plt.plot(t_u.numpy(), seq_model(0.1 * t_u).detach().numpy(), 'kx')
#记住乘以0.1,因为要缩小训练集
plt.show()

# plt.plot(t_u, t_c, 'o')
# plt.plot((t_range).numpy(), seq_model(0.1*t_range).detach().numpy(), 'c-')
# plt.plot(t_u.numpy(), seq_model(0.1*t_u).detach().numpy(), 'kx')
# plt.show()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值