【pytorch】线性神经网络

28 篇文章 0 订阅
21 篇文章 0 订阅

除了使用自己定义模型的方法,也可以用torch提供的神经网络模型。
可以将其理解为只有输入层和输出层的全连接网络。

神经网络

from torch import nn
net = nn.Sequential(nn.Linear(4 , 1))
net[0].weight.data.normal_(0,0.01)
net[0].bias.data.fill_(0)
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.001)

根据全连接网络的特性,不难发现,这就是一个线性回归模型。这也解释了,为什么现在的神经网络层数要如此只深。
因为多层的神经网络可以拟合任意函数,这一点也是被证明了的。

完整代码

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import numpy as np
import torch
from torch.utils import data


# In[2]:


def data_maker(w, b, n_size): # y=w*x+b,n个数据
    X = torch.normal(0 , 1 , (n_size , len(w))) # n*len(w)的参数
    y = torch.matmul(X , w) + b
    y = y + torch.normal(0, 0.01 , y.shape)
    return X , y.reshape((-1 , 1))
W = torch.tensor([4.0 , 2.3 , 121313,312233])
B = 1
x , y = data_maker(W, B, 1000)


# In[3]:


def load_array(data_arrays , batch_size , is_train = True):
    dataset = data.TensorDataset(*data_arrays)
    return data.DataLoader(dataset , batch_size , shuffle = is_train)


# In[4]:


batch_size = 10
data_iter = load_array((x , y) , batch_size)


# In[5]:


from torch import nn
net = nn.Sequential(nn.Linear(4 , 1))
net[0].weight.data.normal_(0,0.01)
net[0].bias.data.fill_(0)
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.001)
epochs = 600


# In[6]:


for epoch in range(epochs):
    for X, Y in data_iter:
        l = loss(net(X), Y)
        trainer.zero_grad()
        l.backward()
        trainer.step()
        pass
    l = loss(net(x) , y)
    print(f'epoch{epoch + 1}, loss {l}')


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值