python - Python 神经网络:“numpy.ndarray”对象没有属性“dim”
问题描述
我正在使用这个数据库建模
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 (most recent call last) in () 2 3 for t in range(200): ----> 4 prediction = net(X_train) # input x and predict based on x 5 6 loss = loss_func(prediction, y_train ) # 必须是(1. nn 输出,2. 目标)
> 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'
解决方案
in prediction = net(X_train)
,X_train
是一个 numpy 数组,但 torch 需要一个张量。
您需要转换为火炬张量,并根据需要移至 gpu
第一行应该是
X_train = torch.from_numpy(df.drop('class', axis=1).to_numpy())
推荐阅读
- javascript - Sequelize - how to use operator AND in association n:n
- android - 通过 gcm 从 firebase 发送通知后对本机应用程序崩溃做出反应
- bash - 如何在 Windows 代理上从 Jenkins groovy 执行 git 命令?
- python - 将 txt 文件的多行与 python 中的单个变量进行比较
- visual-studio-2017 - 我们可以在 Visual Studio 2017 C++ 中构建并且仍然符合 MISRA C++ 吗?
- c# - System.Text.Json:如何将 JsonConverter 应用于具有集合项目的自定义转换器的集合?
- coq - ssreflect 中的字符串比较
- python - 当计数器变大时,它会变得越来越慢吗?
- reactjs - 从 CRA 迁移到 Gatsby 破坏了 JSS 插件
- python - 加载 word2vec 模型时出现数组重塑错误