【问题标题】:RuntimeError: mat1 dim 1 must match mat2 dim 0RuntimeError: mat1 dim 1 必须匹配 mat2 dim 0
【发布时间】:2021-04-17 19:50:45
【问题描述】:

我仍然在努力使用 PyTorch,已经使用了一段时间的 Keras(感觉更直观)。 无论如何 - 我有下面的 nn.linear 模型代码,它只适用于一个输入特征,其中:

inputDim = 1  

我现在正在尝试扩展相同的代码以包含 2 个功能,因此我在我的功能数据框中添加了另一列并设置:

inputDim = 2  

但是,当我运行代码时,我得到了可怕的错误:

RuntimeError: mat1 dim 1 must match mat2 dim 0

此错误引用第 63 行,即:

    outputs = model(inputs)

我在这里浏览了与此维度错误有关的其他几篇文章,但我仍然看不出我的代码有什么问题。任何帮助,将不胜感激。 完整代码如下所示:

import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
import matplotlib.pyplot as plt


device = 'cuda' if torch.cuda.is_available() else 'cpu'

df = pd.read_csv('Adjusted Close - BAC-UBS-WFC.csv')
x = df[['BAC', 'UBS']]
y = df['WFC']

# number_of_features = x.shape[1]
# print(number_of_features)


x_train = np.array(x, dtype=np.float32)
x_train = x_train.reshape(-1, 1)

y_train = np.array(y, dtype=np.float32)
y_train = y_train.reshape(-1, 1)


class linearRegression(torch.nn.Module):
    def __init__(self, inputSize, outputSize):
        super(linearRegression, self).__init__()
        self.linear = torch.nn.Linear(inputSize, outputSize)

    def forward(self, x):
        out = self.linear(x)
        return out


inputDim = 2  
outputDim = 1  
learningRate = 0.01
epochs = 500

# Model instantiation
torch.manual_seed(42)
model = linearRegression(inputDim, outputDim)
if torch.cuda.is_available(): model.cuda()

criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)

# Model training
loss_series = []
for epoch in range(epochs):
    # Converting inputs and labels to Variable
    inputs = Variable(torch.from_numpy(x_train).cuda())
    labels = Variable(torch.from_numpy(y_train).cuda())

    # Clear gradient buffers because we don't want any gradient from previous epoch to carry forward, dont want to cummulate gradients
    optimizer.zero_grad()

    # get output from the model, given the inputs
    outputs = model(inputs)

    # get loss for the predicted output
    loss = criterion(outputs, labels)
    loss_series.append(loss.item())
    print(loss)
    # get gradients w.r.t to parameters
    loss.backward()

    # update parameters
    optimizer.step()

    print('epoch {}, loss {}'.format(epoch, loss.item()))

# Calculate predictions on training data
with torch.no_grad():  # we don't need gradients in the testing phase
    predicted = model(Variable(torch.from_numpy(x_train).cuda())).cpu().data.numpy()


【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    一般建议:对于尺寸错误,在计算的每一步打印出尺寸通常会有所帮助。

    在这种特定情况下,您很可能在使用 x_train = x_train.reshape(-1, 1) 重塑输入时犯了错误

    您的输入是 (N,1),但 NN 需要 (N,2)

    【讨论】:

    • 再次感谢您。我添加了这段代码:“ number_of_features = x.shape[1], input_shape = x.shape, output_shape = y.shape, x_train = np.array(x, dtype=np.float32), x_train = x_train.reshape( input_shape), y_train = np.array(y, dtype=np.float32), y_train = y_train.reshape(output_shape)",现在完美运行了。
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2021-08-02
    • 2021-02-28
    • 1970-01-01
    • 2021-10-12
    • 2018-10-05
    相关资源
    最近更新 更多