最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Converting torch tensor to numpy array using .numpy method gives an error - Stack Overflow

programmeradmin2浏览0评论
>>> a = torch.tensor([[1,2,3],[2,3,4],[3,4,5]])
>>> a
tensor([[1, 2, 3],
        [2, 3, 4],
        [3, 4, 5]])

If we convert this tensor to a numpy array and try to print it, this gives an error

>>> a = a.numpy()
>>> a
AttributeError: module 'numpy.core.multiarray' has no attribute 'generic'

The above exception was the direct cause of the following exception:
...
--> 794 output = repr(obj)
    795 lines = output.splitlines()
    796 with p.group():

RuntimeError: Unable to configure default ndarray.__repr__
>>> a = torch.tensor([[1,2,3],[2,3,4],[3,4,5]])
>>> a
tensor([[1, 2, 3],
        [2, 3, 4],
        [3, 4, 5]])

If we convert this tensor to a numpy array and try to print it, this gives an error

>>> a = a.numpy()
>>> a
AttributeError: module 'numpy.core.multiarray' has no attribute 'generic'

The above exception was the direct cause of the following exception:
...
--> 794 output = repr(obj)
    795 lines = output.splitlines()
    796 with p.group():

RuntimeError: Unable to configure default ndarray.__repr__
Share Improve this question asked Jan 18 at 15:59 GouherDanishGouherDanish 1361 silver badge9 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

This happens because of the numpy version > 1.24

% pip list | grep numpy
numpy                     1.26.4

Let's downgrade the numpy version

% pip install "numpy<1.24" 
Installing collected packages: numpy
  Attempting uninstall: numpy
    Found existing installation: numpy 1.26.4
    Uninstalling numpy-1.26.4:
      Successfully uninstalled numpy-1.26.4
Successfully installed numpy-1.23.5

If we rerun our code, it will convert the tensor to numpy array properly

>>> a = a.numpy()
>>> a
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5]])

If you are really bothered by the version issue but not going to make any changes on the packages, probably you can detour a bit to achieve the goal, e.g.,

import numpy as np
np.array(a.tolist())

and then you will obtain

array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5]])
发布评论

评论列表(0)

  1. 暂无评论