【问题标题】:Size mismatch, m1: [1 x 5], m2: [7 x 100] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:752大小不匹配,m1:[1 x 5],m2:[7 x 100] 在 /pytorch/aten/src/TH/generic/THTensorMath.cpp:752
【发布时间】:2019-10-17 19:18:23
【问题描述】:

我是 pytorch 新手,正在尝试创建模型,但出现此错误,

AttributeError                            Traceback (most recent call last)
<ipython-input-16-a0f31875b0ba> in <module>()
      1 for t in range(100):
      2     # Forward pass
----> 3     y_pred = model(X_train)
      4 
      5     # Accuracy


AttributeError: 'numpy.ndarray' object has no attribute 'dim'

这是我的代码:

x = np.array([2,4,6,18,20,30,50])
y = x * 2
print(x)
print(y)


shuffle_indices = torch.LongTensor(random.sample(range(0, len(x)), 
len(x)))
x = x[shuffle_indices]
y = y[shuffle_indices]

x = torch.from_numpy(x).float()
y = torch.from_numpy(y.ravel()).long()

# Split datasets
test_start_idx = int(len(x) * 0.75)
X_train = x[:test_start_idx] 
y_train = y[:test_start_idx] 
X_test = x[test_start_idx:] 
y_test = y[test_start_idx:]
print("We have %i train samples and %i test samples." % (len(X_train), len(X_test)))

我们有 5 个训练样本和 2 个测试样本。

class MLP(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(MLP, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, output_dim)

    def forward(self, x_in, apply_softmax=False):
        a_1 = F.relu(self.fc1(x_in))
        y_pred = self.fc2(a_1)

        if apply_softmax:
            y_pred = F.softmax(y_pred, dim=1)

        return y_pred

model = MLP(input_dim=len(X_train), 
        hidden_dim=100, 
        output_dim=len(set(y)))
print (model.named_modules)

MLP的绑定方法Module.named_modules((fc1): Linear(in_features=7, out_features=100, bias=True) (fc2):线性(in_features=100,out_features=7,bias=True) )

loss_fn = nn.CrossEntropyLoss()

optimizer = optim.Adam(model.parameters(), lr=1e-3)

def get_accuracy(y_pred, y_target):
    n_correct = torch.eq(y_pred, y_target).sum().item()
    accuracy = n_correct / len(y_pred) * 100
    return accuracy

for t in range(7):
    y_pred = model(X_train)
    _, predictions = y_pred.max(dim=1)
    accuracy = get_accuracy(y_pred=predictions.long(), y_target=y_train)
    loss = loss_fn(y_pred, y_train)
    if t%20==0: 
        print ("epoch: {0} | loss: {1:.4f} | accuracy: {2:.1f}%".format(t, loss, accuracy))
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

【问题讨论】:

  • 能否提供X_train和y_train的样本?
  • 我已经更新了示例代码@zihaozhihao
  • 嗯,你的input_dim 应该是len(X_train) 而不是len(x)
  • 太好了。它解决了我的错误。但现在我选择了另一个。 "AttributeError: 'numpy.ndarray' 对象没有属性 'dim'"
  • 你能更新你当前的代码吗?

标签: deep-learning pytorch mlp


【解决方案1】:

在您的示例中,X_train 是一个需要转换为 torch.Tensornumpy.ndarray 对象。因此,您的问题的解决方案是:

y_pred = model(torch.from_numpy(X_train))

【讨论】:

    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2021-05-13
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多