dvgodoy / PyTorchStepByStep

Official repository of my book: "Deep Learning with PyTorch Step-by-Step: A Beginner's Guide"
https://pytorchstepbystep.com
MIT License
834 stars 310 forks source link

Chapter00:- ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part. #44

Closed AnilSarode closed 11 months ago

AnilSarode commented 11 months ago

Hello, I am getting the error in following code

figure3(x_train, y_train, b, w)

error is


ValueError                                Traceback (most recent call last)
Cell In[11], line 1
----> 1 figure3(x_train, y_train, b, w)

File ~/AIMLDL/Pytorch basic 2/PyTorchStepByStep/plots/chapter0.py:79, in figure3(x_train, y_train, b, w)
     77 ax.scatter([x0], [y0], c='r')
     78 # Vertical line showing error between point and prediction
---> 79 ax.plot([x0, x0], [b + w * x0, y0 - .03], c='r', linewidth=2, linestyle='--')
     80 ax.arrow(x0, y0 - .03, 0, .03, color='r', shape='full', lw=0, length_includes_head=True, head_width=.03)
     81 ax.arrow(x0, b + w * x0 + .05, 0, -.03, color='r', shape='full', lw=0, length_includes_head=True, head_width=.03)

File /usr/lib/python3/dist-packages/matplotlib/axes/_axes.py:1632, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)
   1390 """
   1391 Plot y versus x as lines and/or markers.
   1392 
   (...)
   1629 (``'green'``) or hex strings (``'#008000'``).
   1630 """
   1631 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632 lines = [*self._get_lines(*args, data=data, **kwargs)]
   1633 for line in lines:
   1634     self.add_line(line)

File /usr/lib/python3/dist-packages/matplotlib/axes/_base.py:312, in _process_plot_var_args.__call__(self, data, *args, **kwargs)
    310     this += args[0],
    311     args = args[1:]
--> 312 yield from self._plot_args(this, kwargs)

File /usr/lib/python3/dist-packages/matplotlib/axes/_base.py:488, in _process_plot_var_args._plot_args(self, tup, kwargs, return_kwargs)
    486 if len(xy) == 2:
    487     x = _check_1d(xy[0])
--> 488     y = _check_1d(xy[1])
    489 else:
    490     x, y = index_of(xy[-1])

File /usr/lib/python3/dist-packages/matplotlib/cbook/__init__.py:1304, in _check_1d(x)
   1302 """Convert scalars to 1D arrays; pass-through arrays as is."""
   1303 if not hasattr(x, 'shape') or len(x.shape) < 1:
-> 1304     return np.atleast_1d(x)
   1305 else:
   1306     try:
   1307         # work around
   1308         # https://github.com/pandas-dev/pandas/issues/27775 which
   (...)
   1319         # This code should correctly identify and coerce to a
   1320         # numpy array all pandas versions.

File ~/.local/lib/python3.10/site-packages/numpy/core/shape_base.py:65, in atleast_1d(*arys)
     63 res = []
     64 for ary in arys:
---> 65     ary = asanyarray(ary)
     66     if ary.ndim == 0:
     67         result = ary.reshape(1)

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part. ````
dvgodoy commented 11 months ago

Hi @AnilSarode ,

Thank you for reporting this.

I ran it in Google Colab and it works but it produces a deprecation warning (Colab uses Matplotlib 3.7.1 right now), so I am assuming you're using a more recent version of Matplotlib, is it the case?

Nonetheless, I fixed the code accordingly, so it does not produce the deprecation warning anymore, so I hope it solves your issue. Please let me know if it works well, and if you find any other errors.

Thank you for your support :-)

Best, Daniel

AnilSarode commented 11 months ago

Hi@dvgodoy Thanks a lot for the quick response. Yes, the issue is resolved. I am running the code on my local machine, and using Matplotlib 3.5.1. Could you please explain what exactly you did in the code cause I was trying to figure out and does the error is related to this https://stackoverflow.com/questions/4674473/valueerror-setting-an-array-element-with-a-sequence

dvgodoy commented 11 months ago

Hi @AnilSarode

I'm glad to hear it's working for you now :-)

OK, it seems the warning came from Numpy then, I was re-reading your error message, and the exception is raised from Numpy.

In the code of the original figure3() function in plots/chapter0.py, I was mixing 1-D Numpy arrays (b and w) and individual float values (w0 and x0), so it was complaining:

    ax.plot([x0, x0], [b + w * x0, y0 - .03], c='r', linewidth=2, linestyle='--')
   ...
    ax.arrow(x0, b + w * x0 + .05, 0, -.03, color='r', shape='full', lw=0, length_includes_head=True, head_width=.03)

The only change I made was to retrieve the values from inside the Numpy arrays by adding [0] to them. They had only a single value, so the end result is the same, and the warning is gone because I am not mixing anything:

    ax.plot([x0, x0], [b[0] + w[0] * x0, y0 - .03], c='r', linewidth=2, linestyle='--')
    ...
    ax.arrow(x0, b[0] + w[0] * x0 + .05, 0, -.03, color='r', shape='full', lw=0, length_includes_head=True, head_width=.03)

It's not a problem of types (as suggested by the StackOverflow link) but a problem of mixing elements with different dimensions. I guess Numpy is getting more strict when it comes to those operations.