'can't convert cuda:0 device type tensor to numpy
As metioned in the title, I am getting this TyperError for the following code
I am using google collab and is set to GPU runtime type.
%%time
history = [evaluate(model, valid_dl)]
history
%%time
history += fit_OneCycle(epochs, max_lr, model, train_dl, valid_dl,
grad_clip=grad_clip,
weight_decay=1e-4,
opt_func=opt_func)
def plot_losses(history):
train_losses = [x.get('train_loss') for x in history]
val_losses = [x['val_loss'] for x in history]
plt.plot(train_losses, '-bx')
plt.plot(val_losses, '-rx')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(['Training', 'Validation'])
plt.title('Loss vs. No. of epochs')
for the following line i am getting the error :-
plot_losses(history)
And i am getting the following error message:
AttributeError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/matplotlib/cbook/__init__.py in index_of(y)
1626 try:
-> 1627 return y.index.values, y.values
1628 except AttributeError:
AttributeError: 'builtin_function_or_method' object has no attribute 'values'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
----------------------------------9 frames------------------------------------------
<__array_function__ internals> in atleast_1d(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/torch/_tensor.py in __array__(self, dtype)
676 return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
677 if dtype is None:
--> 678 return self.numpy()
679 else:
680 return self.numpy().astype(dtype, copy=False)
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
Solution 1:[1]
The line of error is not shown here, however, you can replace the array (if it is an array) which you have with:
Thearray.cpu().numpy()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sadcow |