Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Neural Network: 'numpy.ndarray' object has no attribute 'dim'

I am using this database for modeling
http://archive.ics.uci.edu/ml/datasets/Car+Evaluation

after preprocessing

    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()

Error is in this block

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()

Error message

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) # must be (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'
like image 426
SaadiCarnot Avatar asked Jun 12 '20 19:06

SaadiCarnot


1 Answers

in prediction = net(X_train), X_train is a numpy array, but torch expects a tensor.

You need to convert to torch tensor, and move to gpu if you want

the 1st line should be

X_train = torch.from_numpy(df.drop('class', axis=1).to_numpy())
like image 114
Gulzar Avatar answered Nov 13 '22 13:11

Gulzar