'列表索引必须是整数,而不是元组'在python中
问题描述:
我正在研究一个python项目,我无法绘制出一个包含这些值的图表,我无法修正这个错误,因为我无法找出列表。被抛出的错误,我已经提供了以下'列表索引必须是整数,而不是元组'在python中
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
X = [[ 0.24459249,0.11983918,-0.85683004,-0.89438038,-0.50183492],
[-0.7976035,1.95307959,-1.25068375,-0.00678967,-0.25262571],
[ 0.34136607,0.92766956,0.66223556,-1.46454436,-1.60347224],
[ 2.22677877,1.55027737,-0.02381159,-0.05812014,0.17297636],
[ 0.20753675,-1.00847549,-0.13858473,-0.93317858,0.18550176],
[ 1.38946893,-1.03658362,-0.62923293,1.44856682,0.59064268]]
y = [ 0,2,1,0,0,0,3,0,2,1,0,0,2,0,0,0,1,0,
0,0,0,0,1,3,4,0,0,0,0,3,0,2,1,0,0,0,
3,1,3,0,4,0,0,0,1,4,0,4,0,0,0,0,2,0,
1,1,1,1,0,0,2,0,1,0,2,2,1,0,2,1,0,3,
1,1,1,0,1,0,0,3,0,0,0,3,0,0,0,0,0,0,
0,3,0,0,0,1,2,3,0,0,0,0,0,0,3,0,2,1,
2,3,1,1,0,2,2,0,0,0,3,2,3,4,0,3,1,0,
3,3,0,0,0,0,0,0,0,0,4,3,1,0,0,1,0,1,
0,1,4,0,0,0,0,0,0,4,3,1,1,1,2,0,0,4,
0,0,0,0,0,0,1,0,3,0,1,0,4,1,0,1,0,0,
3,2,0,0,1,0,0,2,1,2,0,3,1,2,0,3,0,0,
0,1,0,0,0,0,0,3,3,3,0,1,0,4,0,3,1,0,
0,0,0,0,0,0,0,3,1,0,0,0,3,2,0,2,1,0,
0,3,2,1,0,0,0,0,0,2,0,2,2,1,3,0,0,1,
0,0,0,0,0,0,0,1,0,3,0,0,4,2,2,2,1,0,
1,0,2,0,1,0,0,0,1,0,2,0,3,0,2,4,2,0,
0,0,1,0,2,2,1,0,3,1,1,2,3,1,0]
def plot_2D(data, target, target_names):
colors = cycle('rgbcmykw')
target_ids = range(len(target_names))
plt.figure()
for i, c, label in zip(target_ids, colors, target_names):
plt.scatter(data[target == i, 0], data[target == i, 1],
c=c, label=label)
plt.legend()
plt.savefig('Reduced_PCA_Graph')
target_names = [0,1,2,3,4]
plot_2D(X, y, target_names)
ERROR错误是
Traceback (most recent call last):
File "mat.py", line 49, in <module>
plot_2D(X, y, target_names)
File "mat.py", line 40, in plot_2D
plt.scatter(data[target == i, 0], data[target == i, 1],
TypeError: list indices must be integers, not tuple
答
我不知道,但也许你想有这样的说法:
def plot_2D(data, target, target_names):
colors = cycle('rgbcmykw')
target_ids = range(len(target_names))
plt.figure()
for i, c, label in zip(target_ids, colors, target_names):
plt.scatter(data[target[i]][0], data[target[i]][1], c=c, label=label)
plt.legend()
#plt.savefig('Reduced_PCA_Graph')
plt.show()
请始终包含完整的错误追溯。也就是说,'X',因此'data'是列表的列表。像'data [target == i,0]这样的花式索引只适用于类似numpy的数组对象。 – cel
我认为您的数据集X和Y存在问题,请检查它。 –