笔记-b站刘二大人《pytorch深度学习实践》-第七讲

第七讲-处理多维特征的输入 

激活函数分别用了sigmoid、ReLU、softplus。

比较了一下损失,sigmoid>softplus>ReLU,测得准确率是ReLU>softplus>sigmoid。

附上了代码。

import numpy as np
import torch
import matplotlib.pyplot as plt

xy = np.loadtxt('diabetes.csv.gz',delimiter=',', dtype=np.float32)
x_data = torch.from_numpy(xy[:,:-1])
y_data = torch.from_numpy(xy[:,[-1]])
print('input data.shape',x_data.shape)

class Model(torch.nn.Module):
    def __init__(self):
        super(Model,self).__init__()
        self.linear1 = torch.nn.Linear(8, 6)
        self.linear2 = torch.nn.Linear(6, 4)
        self.linear3 = torch.nn.Linear(4, 1)
        self.sigmoid = torch.nn.Sigmoid()
        self.activate = torch.nn.ReLU()
        self.softplus = torch.nn.Softplus()  #beta->default 1,threshold->default 20


    def forward(self,x):
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))  #sigmoid作为激活函数

        #x = self.activate(self.linear1(x))
        #x = self.activate(self.linear2(x))
        #x = self.sigmoid(self.linear3(x))  #ReLU作为激活函数,最后一层用sigmoid激活

        #x = self.softplus(self.linear1(x))
        #x = self.softplus(self.linear2(x))
        #x = self.sigmoid(self.linear3(x))

        return x

model = Model()

criterion = torch.nn.BCELoss(reduction='mean')  #相当于size_average=True
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

epoch_list = []
loss_list = []
for epoch in range(5000):
    y_pred = model(x_data)   #forward:predict
    loss = criterion(y_pred, y_data)  #forward:loss
    print(epoch,loss.item())

    epoch_list.append(epoch)
    loss_list.append(loss)

    optimizer.zero_grad()
    loss.backward()  # backward: autograd,自动计算梯度
    optimizer.step()  #update 参数,更新w和b的值

    if epoch % 500 == 499:
        y_pred_label = torch.where(y_pred >= 0.5, torch.tensor([1.0]), torch.tensor([0.0]))
        acc = torch.eq(y_pred_label, y_data).sum().item() / y_data.size(0)
        print("loss = ", loss.item(), "acc = ", acc)


plt.plot(epoch_list,loss_list) #画图
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值