简体   繁体   English

在 python 上绘制带有颜色的特征时出现“ValueError”

[英]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 .我想可视化我的数据,然后 plot 带有颜色的特征,但是在分配颜色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.请注意, data_t由 1 和 0 组成。

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

%matplotlib inline

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

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()

Your problem is that the arrays data_c1 , data_c2 and data_t seem to have more that one dimension.您的问题是 arrays data_c1data_c2data_t似乎不止一维。 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.变量t不是标量而是 NumPy 数组,并且t == 1对于非标量 NumPy 对象是不明确的。 I would suggest you to ravel (ie flatten) all your arrays:我建议你拆开(即展平)你所有的 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM