Pytorch学习(七)——多维特征输入

 课程:07.处理多维特征的输入_哔哩哔哩_bilibili

模型如图所示:8维到6维到4维到1维

数据集为自己照着课件里的数据输入的,其中每个数据以\t隔开

import numpy as np
import torch
import matplotlib.pyplot as plt
xy = np.loadtxt('data1.txt', delimiter = '\t', dtype = np.float32)#因为我的txt中数据之间是用\t隔开,所以delimiter = '\t'

x_data = torch.from_numpy(xy[:,:-1])#逗号前为行,都需要;逗号后为列除了最后一列都需要
y_data = torch.from_numpy(xy[:,[-1]])#逗号前为行,都需要;逗号后为列只需要最后一列

loss_list = []
Epoch_list = []

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.activate = torch.nn.Sigmoid()#也可以使用其他激活函数,如torch.nn.ReLU()
        
    def forward(self, x):
        x = self.activate(self.linear1(x))
        x = self.activate(self.linear2(x))
        x = self.activate(self.linear3(x))
        return x

model = Model()

criterion = torch.nn.BCELoss(size_average = True)#返回loss均值 
optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)

for epoch in range(100):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())
    loss_list.append(loss.item())
    Epoch_list.append(epoch)
    optimizer.zero_grad()#权重梯度清零
    loss.backward()#反馈
    optimizer.step()#权重更新
    
plt.plot(Epoch_list, loss_list)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()

结果:

打印x_data和y_data的数据如下:

tensor([[-0.2900,  0.4900,  0.1800, -0.2900,  0.0000,  0.0000, -0.5300, -0.0300],
        [-0.8800, -0.1500,  0.0800, -0.4100,  0.0000, -0.2100, -0.7700, -0.6700],
        [-0.0600,  0.8400,  0.0500,  0.0000,  0.0000, -0.3100, -0.4900, -0.6300],
        [-0.8800, -0.1100,  0.0800, -0.5400, -0.7800, -0.1600, -0.9200,  0.0000],
        [ 0.0000,  0.3800, -0.3400, -0.2900, -0.6000,  0.2800,  0.8900, -0.6000],
        [-0.4100,  0.1700,  0.2100,  0.0000,  0.0000, -0.2400, -0.8900, -0.7000],
        [-0.6500, -0.2200, -0.1800, -0.3500, -0.7900, -0.0800, -0.8500, -0.8300],
        [ 0.1800,  0.1600,  0.0000,  0.0000,  0.0000,  0.0500, -0.9500, -0.7300],
        [-0.7600,  0.9800,  0.1500, -0.0900,  0.2800, -0.0900, -0.9300,  0.0700],
        [-0.0600,  0.2600,  0.5700,  0.0000,  0.0000,  0.0000, -0.8700,  0.1000]])
tensor([[0.],
        [1.],
        [0.],
        [1.],
        [0.],
        [1.],
        [0.],
        [1.],
        [0.],
        [0.]])

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值