Python PyTorch运行时错误:参数#1和#x27的张量;自我';在CPU上,但期望它们在GPU上

Python PyTorch运行时错误:参数#1和#x27的张量;自我';在CPU上,但期望它们在GPU上,python,deep-learning,pytorch,logistic-regression,Python,Deep Learning,Pytorch,Logistic Regression,我正在使用PyTorch进行我的逻辑回归模型,但每当我运行模型摘要时,我都会得到一个错误 RuntimeError:“out”的张量在CPU上,参数#1“self”的张量在CPU上,但预期它们在GPU上(检查addmm的参数时) 代码 # Convert data to tensors X_train = torch.Tensor(X_train) y_train = torch.LongTensor(y_train) X_test = torch.Tensor(X_test) y_test =

我正在使用PyTorch进行我的逻辑回归模型,但每当我运行模型摘要时,我都会得到一个错误

RuntimeError:“out”的张量在CPU上,参数#1“self”的张量在CPU上,但预期它们在GPU上(检查addmm的参数时)

代码

# Convert data to tensors
X_train = torch.Tensor(X_train)
y_train = torch.LongTensor(y_train)
X_test = torch.Tensor(X_test)
y_test = torch.LongTensor(y_test)

class LogisticRegression(nn.Module):
    def __init__(self, input_features, num_classes):
        super(LogisticRegression, self).__init__()
        self.fc1 = nn.Linear(input_dim, num_classes)
        
    def forward(self, x_in, apply_softmax = False):
        y_pred = self.fc1(x_in)
        if apply_softmax:
            y_pred = F.softmax(y_pred, dim = 1)
        return y_pred

INPUT_DIM = X_train.shape[1]
NUM_CLASSES = len(y_train.unique())

model = LogisticRegression(input_features = INPUT_DIM, num_classes = NUM_CLASSES)
print(model.named_parameters)
summary(model, input_size=(INPUT_DIM,))

我的方法不符合预期,我如何着手解决问题?

如果您使用的是笔记本电脑,那么您很可能已经混淆了变量。As
input\u dim
未在代码段中定义,但以前可能在您的范围内

假设您使用的是
torchsummary
中的
summary
,则不需要数据来推断模型的结构,只需要输入形状。以下工作将起作用:

class LogisticRegression(nn.Module):
    def __init__(self, input_features, num_classes):
        super(LogisticRegression, self).__init__()
        self.fc1 = nn.Linear(input_features, num_classes) # <- was input_dim
        
    def forward(self, x_in, apply_softmax = False):
        y_pred = self.fc1(x_in)
        if apply_softmax:
            y_pred = F.softmax(y_pred, dim = 1)
        return y_pred

INPUT_DIM = 10
NUM_CLASSES = 100

model = LogisticRegression(input_features=INPUT_DIM, num_classes=NUM_CLASSES)
summary(model, input_size=(INPUT_DIM,))
类逻辑回归(nn.Module):
定义初始化(自、输入特性、num类):
超级(逻辑回归,自我)。\uuuu初始
self.fc1=nn.Linear(输入特征,num类)#我也有同样的错误

RuntimeError:“out”的张量在CPU上,参数#1“self”的张量在CPU上,但预期它们在GPU上(检查addmm的参数时)

确保模型及其权重位于GPU上有助于:

model.to(device)
定义设备时:

device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")

你能把self.fc1=torch.nn.ModuleList(self.fc1)
添加到
\uuuu init\uuuuu
中并告诉它是否可行吗?@Anirbansha我添加了,但得到了一个错误
TypeError:ModuleList.extend应该用iterable调用,但得到了线性的
知道为什么吗?@ShadowWalker模块列表的这个输入需要是一个列表。所以
self.fc1=torch.nn.ModuleList([self.fc1])
。但是我不认为这能解决你的问题:nn.Linear已经继承了nn.Module,所以把它放在ModuleList中不会改变你现在的情况。你能试着用这段代码来推断而不是总结吗?然后我就可以重新创建你的代码了。请注意,你的代码和我的代码没有明显的变化。请看第4行:
input\u dim
被替换为
input\u功能
。我应用了你指出的变化,但这并没有解决问题。错误仍然存在。您确切使用的是哪个火炬摘要包?
来自火炬摘要导入摘要