我将PyTorch用于我的Logistic Regression模型,但每当我运行模型摘要时,我都会收到错误
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,))
我的方法没有按预期工作,我该如何解决问题?
我也有同样的错误。
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")
如果您使用的是笔记本,那么您很可能混淆了变量。因为input_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,))