我在下面发布的代码只是应用程序的一小部分:
def train(self, training_reviews, training_labels):
# make sure out we have a matching number of reviews and labels
assert(len(training_reviews) == len(training_labels))
# Keep track of correct predictions to display accuracy during training
correct_so_far = 0
# Remember when we started for printing time statistics
start = time.time()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(self.parameters(), lr=self.learning_rate)
# loop through all the given reviews and run a forward and backward pass,
# updating weights for every item
for i in range(len(training_reviews)):
# TODO: Get the next review and its correct label
review = training_reviews[i]
label = training_labels[i]
print('processing item ',i)
self.update_input_layer(review)
output = self.forward(torch.from_numpy(self.layer_0).float())
target = self.get_target_for_label(label)
print('output ',output)
print('target ',target)
loss = criterion(output, target)
...
mlp = SentimentNetwork(reviews[:-1000],labels[:-1000], learning_rate=0.1)
mlp.train(reviews[:-1000],labels[:-1000])
,并且在评估时以标题行中的异常结尾:
loss = criterion(output, target)
在此之前,变量如下:
output tensor([[0.5803]], grad_fn=<SigmoidBackward>)
target 1
答案 0 :(得分:1)
目标应为torch.Tensor
变量。使用torch.tensor([target])
。
此外,您可能希望使用批次(因此,有N
个样本,torch.tensor
的形状为(N,)
,与target
相同)。
有关PyTorch的信息,请参见introductory tutorial,因为您可能没有使用批处理,未运行优化器或未使用torch.utils.data.Dataset
和torch.utils.data.DataLoader
。