Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting `ValueError` when plotting features with colours on python

I have the following data which needs to be linearly classified using least squares. I wanted to visualise my data and then plot the features with colours but I got the following error when assigning the colour colour_cond.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Note that data_t is made of 1s and 0s.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import numpy as np
import matplotlib.pyplot as plt
import glob
from scipy.io import loadmat

%matplotlib inline

data = loadmat('Mydata_A.mat')
data_c1 = np.array([loadmat(entry, variable_names= ("X"), squeeze_me=True)["X"][:,0] for entry in entries])
data_c2 = np.array([loadmat(entry, variable_names= ("X"), squeeze_me=True)["X"][:,1] for entry in entries])
data_t = np.array([loadmat(entry, variable_names= ("T"), squeeze_me=True)["T"][:] for entry in entries])

colour_cond=['red' if t==1 else 'blue' for t in data_t]
plt.scatter(data_c1,data_c2,colour=colour_cond)
plt.xlabel('X1')
plt.ylabel('X2')
plt.title('Training Data (X1,X2)')
plt.show()

>Solution :

Your problem is that the arrays data_c1, data_c2 and data_t seem to have more that one dimension. In your following line:

colour_cond=['red' if t==1 else 'blue' for t in data_t]

the variable t is not a scalar but a NumPy array, and t == 1 is ambiguous for non-scalar NumPy objects. I would suggest you to ravel (i.e. flatten) all your arrays:

import glob
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat

%matplotlib inline

data = loadmat('Mydata_A.mat')
data_c1 = np.array([
    loadmat(entry, variable_names=("X"), squeeze_me=True)["X"][:, 0]
    for entry in entries]).ravel()
data_c2 = np.array([
    loadmat(entry, variable_names=("X"), squeeze_me=True)["X"][:, 1]
    for entry in entries]).ravel()
data_t = np.array([
    loadmat(entry, variable_names=("T"), squeeze_me=True)["T"][:]
    for entry in entries]).ravel()

colour_cond = ['red' if t==1 else 'blue' for t in data_t]
plt.scatter(data_c1, data_c2, color=colour_cond)
plt.xlabel('X1')
plt.ylabel('X2')
plt.title('Training Data (X1,X2)')
plt.show()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading