Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib scatter: TypeError: unhashable type: 'numpy.ndarray'

I'm getting the following error:

TypeError                                 Traceback (most recent call last)
~/.local/share/miniconda3/lib/python3.6/site-packages/matplotlib/colors.py in to_rgba(c, alpha)
    154     try:
--> 155         rgba = _colors_full_map.cache[c, alpha]
    156     except (KeyError, TypeError):  # Not in cache, or unhashable.

TypeError: unhashable type: 'numpy.ndarray'

The code in question is from a .ipynb downloaded from Coursera.

It works fine on their system, but it seems that I have a library versioning problem locally.

The code is:

plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
like image 421
Tom Hale Avatar asked Apr 15 '18 09:04

Tom Hale


People also ask

How do I fix Unhashable type Numpy Ndarray?

We can solve this by adding each array element instead of the array object into the set. This should add all the elements of the array to the set.

What is an Unhashable type?

What are Unhashable Type Errors in Python? Unhashable type errors appear in a Python program when a data type that is not hashable is used in code that requires hashable data. An example of this is using an element in a set or a list as the key of a dictionary.

What is TypeError Unhashable type list?

TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can't be hashed.


1 Answers

Change:

plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)

to:

plt.scatter(X[0, :], X[1, :], c=y.ravel().tolist(), cmap=plt.cm.Spectral)

This flattens the array y to be one-dimensional, and then turns it into a list, which to_rgba is happy to digest as something it can hash.


Coursera Deep Learning students:

You'll likely find the offending line(s) of code in one of the *util*.py files. Look for scatter in the traceback to get the filename.

I saw this question raised about 8 times on the forum. Please upvote both question and answer if they've been useful.

like image 97
Tom Hale Avatar answered Nov 15 '22 03:11

Tom Hale