[Python] Python code snippet raising error: "TypeError: can only be called with ndarray object"

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am testing a code snippet on Dive into deep learning. When I try running the following code, it bumps out error at line print(A). I search for explanations on ChatGPT, DeepSeek, etc. But I still don't understand the reasons behind this, and the solution to this problem.

    Any advice would be appreciated! :)

    A = X.numpy()
    print(A.shape)
    print(A)
    B = torch.tensor(A)
    type(A), type(B)


    Detailed output:

    (3, 4)
    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    Cell In[39], line 3
    1 A = X.numpy()
    2 print(A.shape)
    ----> 3 print(A)
    4 B = torch.tensor(A)
    5 type(A), type(B)

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:1669, in _array_str_implementation(a, max_line_width, precision, suppress_small, array2string)
    1663 if a.shape == ():
    1664 # obtain a scalar and call str on it, avoiding problems for subclasses
    1665 # for which indexing with () returns a 0d instead of a scalar by using
    1666 # ndarray's getindex. Also guard against recursive 0d object arrays.
    1667 return _guarded_repr_or_str(np.ndarray.__getitem__(a, ()))
    -> 1669 return array2string(a, max_line_width, precision, suppress_small, ' ', "")

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:762, in array2string(a, max_line_width, precision, suppress_small, separator, prefix, style, formatter, threshold, edgeitems, sign, floatmode, suffix, legacy)
    759 if a.size == 0:
    760 return "[]"
    --> 762 return _array2string(a, options, separator, prefix)

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:534, in _recursive_guard.<locals>.decorating_function.<locals>.wrapper(self, *args, **kwargs)
    532 repr_running.add(key)
    533 try:
    --> 534 return f(self, *args, **kwargs)
    535 finally:
    536 repr_running.discard(key)

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:567, in _array2string(a, options, separator, prefix)
    564 # skip over array(
    565 next_line_prefix += " "*len(prefix)
    --> 567 lst = _formatArray(a, format_function, options['linewidth'],
    568 next_line_prefix, separator, options['edgeitems'],
    569 summary_insert, options['legacy'])
    570 return lst

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:921, in _formatArray(a, format_function, line_width, next_line_prefix, separator, edge_items, summary_insert, legacy)
    917 return s
    919 try:
    920 # invoke the recursive part with an initial index and prefix
    --> 921 return recurser(index=(),
    922 hanging_indent=next_line_prefix,
    923 curr_width=line_width)
    924 finally:
    925 # recursive closures have a cyclic reference to themselves, which
    926 # requires gc to collect (gh-10620). To avoid this problem, for
    927 # performance and PyPy friendliness, we break the cycle:
    928 recurser = None

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:908, in _formatArray.<locals>.recurser(index, hanging_indent, curr_width)
    905 s += hanging_indent + summary_insert + line_sep
    907 for i in range(trailing_items, 1, -1):
    --> 908 nested = recurser(index + (-i,), next_hanging_indent,
    909 next_width)
    910 s += hanging_indent + nested + line_sep
    912 nested = recurser(index + (-1,), next_hanging_indent, next_width)

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:874, in _formatArray.<locals>.recurser(index, hanging_indent, curr_width)
    871 line += separator
    873 for i in range(trailing_items, 1, -1):
    --> 874 word = recurser(index + (-i,), next_hanging_indent, next_width)
    875 s, line = _extendLine_pretty(
    876 s, line, word, elem_width, hanging_indent, legacy)
    877 line += separator

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:825, in _formatArray.<locals>.recurser(index, hanging_indent, curr_width)
    822 axes_left = a.ndim - axis
    824 if axes_left == 0:
    --> 825 return format_function(a[index])
    827 # when recursing, add a space to align with the [ added, and reduce the
    828 # length of the line by 1
    829 next_hanging_indent = hanging_indent + ' '

    File ~/miniconda3/envs/d2l/lib/python3.9/site-packages/numpy/_core/arrayprint.py:1053, in FloatingFormat.__call__(self, x)
    1052 def __call__(self, x):
    -> 1053 if not np.isfinite(x):
    1054 with errstate(invalid='ignore'):
    1055 if np.isnan(x):

    TypeError: can only be called with ndarray object

    Continue reading...

Compartilhe esta Página