用PyTorch实现多层网络

用PyTorch实现多层网络

import torch.nn.functional as F
import torch.nn.init as init
import torch
from torch.autograd import Variable
import matplotlib.pyplot as  plt
import math

from sklearn import  datasets

diabetes = datasets.load_diabetes()
print(diabetes.data)
print(diabetes.target)

x_data = Variable(torch.from_numpy(diabetes.data))
y_data = Variable(torch.from_numpy(diabetes.target))
print(x_data.data.shape)
print(y_data.data.shape)
x_data = x_data.float()
y_data = y_data.float()

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.l1 = torch.nn.Linear(10, 6)
        self.l2 = torch.nn.Linear(6, 4)
        self.l3 = torch.nn.Linear(4, 1)

    def forward(self, x):
        out1 = F.relu(self.l1(x))
        out2 = F.dropout(out1, p= 0.5)
        out3 = F.relu(self.l2(out2))
        out4 = F.dropout(out3, p=0.5)
        y_pred = F.sigmoid(self.l3(out3))
        return y_pred

def weights_init(m):
    classname= m.__class__.__name__
    if classname.find('Linear') !=  -1:
        m.weight.data = torch.randn(m.weight.data.size()[0], m.weight.data.size()[1])
        m.bias.data = torch.randn(m.bias.data.size()[0])

model = Model()
model.apply(weights_init)

criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)

Loss=[]
for epoch in range(100):
        y_pred = model(x_data)
        loss = criterion(y_pred, y_data)
        if epoch%5 == 0:
            print("epoch =", epoch, "loss", loss.item())
            Loss.append(loss.item())
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

hour_var = Variable(torch.randn(1, 10))
print("predict", model(hour_var).data[0]>0.5)

plt.plot(loss.detach().numpy())
plt.show()





IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

将loss.data[0] 改为loss.item()

size mismatch, m1: [442 x 10], m2: [8 x 6]

torch.Size([442, 10]), 所以改为self.l1 = torch.nn.Linear(10, 6)

RuntimeError: Can’t call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

plt.plot(loss.detach().numpy())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值