pytorch深度学习基础 8(简单的神经网络替换线性模型)

接上一节的思路,这一节我们将使用神经网络来代替我们的之前的线性模型作为逼近函数。我们将保持其他的一切不变,只重新定义模型,小编这里构建的是最简单的神经网络,一个线性模块,一个激活函数,然后一个线性模块。

seq_model = nn.Sequential(OrderedDict([
    ('hidden_linear', nn.Linear(1, 8)),
    ('hidden_activation', nn.Tanh()),
    ('output_linear', nn.Linear(8, 1))
]))

这个代码片段定义了一个简单的神经网络模型,使用nn.SequentialOrderedDict来组织模型的层。这个模型包含一个隐藏层和一个输出层,隐藏层使用Tanh激活函数。

模型结构

  1. 隐藏层 (hidden_linear):
    • 输入维度: 1
    • 输出维度: 8
    • 线性变换: nn.Linear(1, 8)
  2. 激活函数 (hidden_activation):
    • 激活函数: Tanh (nn.Tanh())
  3. 输出层 (output_linear):
    • 输入维度: 8
    • 输出维度: 1
    • 线性变换: nn.Linear(8, 1)
for name, param in seq_model.named_parameters():
    print(name, param.shape)

seq_model.named_parameters() 方法用于遍历模型中的所有参数,并返回每个参数的名称(name)和参数本身(params)

其他的没有变化

from collections import OrderedDict

seq_model = nn.Sequential(OrderedDict([
    ('hidden_linear', nn.Linear(1, 8)),
    ('hidden_activation', nn.Tanh()),
    ('output_linear', nn.Linear(8, 1))
]))

optimizer = optim.SGD(seq_model.parameters(), lr=1e-4)  # <1>

training_loop(
    n_epochs=100000,
    optimizer=optimizer,
    model=seq_model,
    loss_fn=nn.MSELoss(),
    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)

from matplotlib import pyplot as plt

t_range = torch.arange(20., 90.).unsqueeze(1)

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-')
plt.plot(t_u.numpy(), seq_model(0.1 * t_u).detach().numpy(), 'kx')
plt.show()

 可以看到即使使用神经网络进行训练还是有点过拟合的现象发生,总的来说做的还不错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值