gpt4 book ai didi

neural-network - ValueError : Target size (torch. Size([1000])) must be the same as input size (torch.Size([1000, 1]))

转载 作者:行者123 更新时间:2023-12-05 02:02:58 33 4
gpt4 key购买 nike

我正在尝试在 pyTorch 中训练我的第一个神经网络(我不是程序员,只是一个困惑的化学家)。

网络本身应该采用 1064 个元素向量并用 float 对它们进行评级。

到目前为止,我遇到了各种各样的错误,从“float instead of long”到“Target 1 is out of bounds”。因此,我重新定义了数据类型,更正了输入向量的维度,更改了损失函数,现在我陷入了更正当前错误让我回到之前错误的情况。

这是:

ValueError: Target size (torch.Size([1000])) must be the same as input size (torch.Size([1000, 1]))

'loss=loss_calc(outputs, target)' 行。

我尝试在 DataSet 类定义期间取消压缩标签,但这个解决方案让我退缩了。当我尝试 label = label.view(1,1) 时,结果错误更改为

Target size (torch.Size([1000, 1, 1])) must be the same as input size (torch.Size([1000, 1]))

谁能帮我解决这个问题?

import pandas as pd
import numpy as np
import rdkit
from rdkit import Chem
from rdkit.Chem import AllChem
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader

class dataset(Dataset):
def __init__(self, path, transform=None):
self.data = pd.read_excel(path)
self.transform = transform

def __len__(self):
return len(self.data)

def __getitem__(self, index):
smiles=self.data.at[index, 'smiles']
mol=Chem.MolFromSmiles(smiles)
morgan = torch.tensor(list(AllChem.GetMorganFingerprintAsBitVect(mol, 1, nBits=1064)), dtype=torch.float)

label=torch.tensor(self.data.at[index, 'score'], dtype=torch.long)

if self.transform is not None:
morgan=self.transform(morgan)

return morgan, label

class Net(nn.Module):

def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(1064, 1064)
self.fc2 = nn.Linear(1064, 1)
self.act = nn.Tanh()

def forward(self, x):
x = self.act(self.fc1(x))
x = self.act(self.fc2(x))
x = self.fc2(x)
return x

trainSet=dataset(r'C:\Users\BajMic\Peptides\trainingSet.xlsx')
testSet=dataset(r'C:\Users\BajMic\Peptides\testSet.xlsx')

net = Net()
loss_calc = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for epoch in range(2):
running_loss=0.0
for data in DataLoader(trainSet, batch_size=1000, shuffle=True):
inputs, target = data
optimizer.zero_grad()
outputs = net(inputs)
print(outputs)
loss = loss_calc(outputs, target)
loss.backward()
optimizer.step() # print statistics
running_loss += loss.item()
print('[%d, %5d] loss: %.3f' %(epoch + 1, i + 1, running_loss))
running_loss = 0.0
print('Finished Training')

最佳答案

当使用损失函数并遇到形状问题时,您通常会收到此类错误消息:

Target size (torch.Size([...])) must be the same as input size (torch.Size([...]))

“目标” 指的是标签,即基本事实,而 “输入” 指的是模型的输出。在这种情况下,输出是 1 个标量值的 1000 个预测(您设置 batch_size=1000)。因此形状是 (1000, 1)。最后一个轴是困扰您的轴,因为预测向量只是一个包含 1000 个标量的一维张量,即 (1000)

要解决这个问题,您可以使用额外的维度扩展目标张量。用torch.unsqueeze() :

target = target.unsqueeze(-1) # -1 stands for last here equivalent to 1

关于neural-network - ValueError : Target size (torch. Size([1000])) must be the same as input size (torch.Size([1000, 1])),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65537991/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com