【问题标题】:Python Neural Network: 'numpy.ndarray' object has no attribute 'dim'Python 神经网络:“numpy.ndarray”对象没有属性“dim”
【发布时间】:2020-10-02 16:00:06
【问题描述】:

我正在使用这个数据库进行建模
http://archive.ics.uci.edu/ml/datasets/Car+Evaluation

预处理后

    X_train = df.drop('class', axis=1).to_numpy()
    y_train = df['class'].to_numpy()

    X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2)

class network(nn.Module):


def __init__(self, input_size, hidden1_size, hidden2_size, num_classes):
    super(network, self).__init__()
    self.fc1 = nn.Linear(input_size, hidden1_size)
    self.relu1 = nn.ReLU()
    self.fc2 = nn.Linear(hidden1_size, hidden2_size)
    self.relu2 = nn.ReLU()
    self.fc3 = nn.Linear(hidden2_size, num_classes)

  def forward(self, x):
    out = self.fc1(x)
    out = self.relu1(out)
    out = self.fc2(out)
    out = self.relu2(out)
    out = self.fc3(out)
    return out

net = network(input_size=6, hidden1_size=5, hidden2_size=4, num_classes=4)
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss()

错误在这个块中

plt.ion()

for t in range(200):
    prediction = net(X_train)     # input x and predict based on x

    loss = loss_func(prediction, y_train)     # must be (1. nn output, 2. target)

    optimizer.zero_grad()   # clear gradients for next train
    loss.backward()         # backpropagation, compute gradients
    optimizer.step()        # apply gradients

    if t % 5 == 0:
        # plot and show learning process
        plt.cla()
        plt.scatter(x.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
        plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color':  'red'})
        plt.pause(0.1)

plt.ioff()
plt.show()

错误信息

AttributeError Traceback(最近一次调用最后一次) 在 () 2 3 对于范围内的 t(200): ----> 4 prediction = net(X_train) # 输入x并根据x进行预测 5 6 loss = loss_func(prediction, y_train) #必须是(1.nn输出,2.target)

> 4 frames /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py
> in linear(input, weight, bias)    1606         if any([type(t) is not
> Tensor for t in tens_ops]) and has_torch_function(tens_ops):    1607  
> return handle_torch_function(linear, tens_ops, input, weight,
> bias=bias)
> -> 1608     if input.dim() == 2 and bias is not None:    1609         # fused op is marginally faster    1610         ret = torch.addmm(bias, input, weight.t())
> 
> AttributeError: 'numpy.ndarray' object has no attribute 'dim'

【问题讨论】:

  • prediction = net(X_train)改成prediction = net(tensor(X_train) )?

标签: python numpy pytorch attributeerror


【解决方案1】:

prediction = net(X_train) 中,X_train 是一个 numpy 数组,但 torch 需要一个张量。

你需要转换成torch张量,如果你愿意,可以移动到gpu

第一行应该是

X_train = torch.from_numpy(df.drop('class', axis=1).to_numpy())

【讨论】:

  • 这可能无法完全正常工作,因为您没有提供完整的代码。
猜你喜欢
  • 2018-01-27
  • 2017-03-06
  • 2017-08-14
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 2020-02-21
  • 2020-12-08
  • 2019-12-10
相关资源
最近更新 更多