使用pytorch训练神经网络时出现“AttributeError: ‘classificadorFinal’ object has no attribute ‘log_softmax’”错误

我在学习使用pytorch时遇到了一个错误,导致无法继续编程。

我的代码如下:

import torch.nn as nnfrom skorch import NeuralNetClassifier #integracao com sklearnfrom sklearn.model_selection import cross_val_score,GridSearchCVfrom sklearn.preprocessing import LabelEncoder, MinMaxScalerimport torchimport torch.nn.functional as Ffrom torch import nn,optimclass classificadorFinal(nn.Module):    def __init__(self, activation=F.tanh, neurons=16, initializer=torch.nn.init.uniform_, dropout=0.3):        ##from melhores_parametros        super().__init__()        self.dense0 = nn.Linear(4, neurons)        initializer(self.dense0.weight)        self.activation0 = activation        self.dense1 = nn.Linear(neurons, neurons)        initializer(self.dense1.weight)        self.activation1 = activation        self.dense2 = nn.Linear(neurons, 3)        self.dropout = nn.Dropout(dropout)    def forward(self, X):        X = self.dense0(X)        X = self.activation0(X)        X = self.dropout(X)        X = self.dense1(X)        X = self.activation1(X)        X = self.dropout(X)        X = self.dense2(X)        return Xcriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(classificador.parameters(), lr = 0.001, weight_decay = 0.0001)#treinofor epoch in range(200):##from melhores_parametros    running_loss = 0.    running_accuracy = 0.    for data in train_loader:        inputs, labels = data        optimizer.zero_grad()                outputs = classificadorFinal(inputs)        loss = criterion(outputs, labels)###erro        loss.backward()        optimizer.step()        running_loss += loss.item()        ps = F.softmax(outputs)        top_p, top_class = ps.topk(k = 1, dim = 1)        equals = top_class == labels.view(*top_class.shape)        running_accuracy += torch.mean(equals.type(torch.float))    print('Época {:3d}: perda {:3.5f} - precisão {:3.5f}'.format(epoch + 1, running_loss/len(train_loader), running_accuracy/len(train_loader)))

错误正好发生在loss = criterion(outputs, labels)这一行:

AttributeError: ‘classificadorFinal’ object has no attribute ‘log_softmax’

我发现这个错误是众所周知的,但我没有理解提出的解决方案:

disable aux_logits 在创建模型时设置aux_logits=False.

请帮帮我!


回答:

输出实际上并不是模型的输出,而是模型本身。classificadorFinal是一个类,调用它会创建该类的对象/实例,而inputs将作为__init__方法的第一个参数,即activation

# 创建模型的实例outputs = classificadorFinal(inputs)

你首先需要创建模型(一个实例),这应该只做一次,然后用inputs调用该模型。看起来你之前已经创建了模型,因为你在优化器中使用了classificador.parameters(),因此classificador可能是模型的实例。你需要调用classificador(实例)而不是classificadorFinal(类)来创建输出。

# 调用模型的实例,而不是类 outputs = classificador(inputs)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注