gpt4 book ai didi

Python 神经网络 : 'numpy.ndarray' object has no attribute 'dim'

转载 作者:行者123 更新时间:2023-12-04 04:28:55 35 4
gpt4 key购买 nike

我正在使用这个数据库进行建模
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)
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 回溯(最近一次调用最后一次)
在 ()
2
3 对于范围内的 t(200):
----> 4 prediction = net(X_train) # 输入x并根据x进行预测
5
6 loss = loss_func(prediction, y_train) # 必须是(1.nn output, 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) , X_train是一个 numpy 数组,但 torch 需要一个张量。

您需要转换为火炬张量,并根据需要移动到 gpu

第一行应该是

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

关于Python 神经网络 : 'numpy.ndarray' object has no attribute 'dim' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62350980/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com