【问题标题】:Python IndexError: index 1 is out of bounds for LDAPython IndexError:索引 1 超出 LDA 范围
【发布时间】:2016-06-03 06:38:16
【问题描述】:

我有一个如下所示的数据集:

    Out  Revolver   Ratio     Num ...
0   1    0.766127   0.802982  0   ...
1   0    0.957151   0.121876  1 
2   0    0.658180   0.085113  0 
3   0    0.233810   0.036050  3 
4   1    0.907239   0.024926  5 
...

Out 只能取值 0 和 1。 然后,我尝试使用与此处类似的以下代码生成 PCA 和 LCA 图:http://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_vs_lda.html

features = Train.columns[1:]
Xf = newTrain[features]
yf = newTrain.Out
pca = PCA(n_components=2)
X_r = pca.fit(Xf).transform(Xf)
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(Xf, yf).transform(Xf)

plt.figure()
for c, i, name in zip("rgb", [0, 1], names):
    plt.scatter(X_r[yf == i, 0], X_r[yf == i, 1], c=c, label=name)
plt.legend()
plt.title('PCA plt')

plt.figure()
for c, i, name in zip("rgb", [0, 1], names):
    plt.scatter(X_r2[yf == i, 0], X_r2[yf == i, 1], c=c, label=name)
plt.legend()
plt.title('LDA plt')

我可以让 PCA 情节发挥作用。但是,它没有意义,因为它只显示 2 个点。一个在 (-4000, 30) 左右,另一个在 (2400, 23.7)。我没有在该链接的图中看到一堆数据点

LDA 绘图不起作用并给出错误

IndexError: 索引 1 超出轴 1 的范围,大小为 1

我也尝试了下面的代码来生成 LDA 图,但得到了同样的错误

for c, i, name in zip("rgb", [0, 1], names):
    plt.scatter(x=X_LDA_sklearn[:, 0][yf==i], y=X_LDA_sklearn[:, 1][yf==i], c=c, label=name)
plt.legend()

有人知道这是怎么回事吗?

编辑:这是我的导入

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import csv

from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.lda import LDA

至于错误发生在哪里:

我明白了

FutureWarning: in the future, boolean array-likes will be handled as a boolean array index
plt.scatter(X_r[yf == i,0], X_r[yf == i, 1], c=c, label=name)

在 for 循环内 PCA 图的行

至于线路上的LDA

plt.scatter(X_r2[yf == i, 0], X_r2[yf == i, 1], c=c, label=name)

我明白了

FutureWarning: in the future, boolean array-likes will be handled as a boolean array index

IndexError: index 1 is out of bounds for axis 1 with size 1

【问题讨论】:

  • 您能否添加您的import 语句并让我们知道发生错误的行?
  • TrainnewTrain 是如何定义的?你如何读入数据?这显然是一个维度问题,所以如果你告诉我们你是如何创建你正在使用的数据的,那将会有很大帮助。 :)
  • 你可以在 pastebin.com/bDee3TtZ 看到我的代码 我在那个 pastebin 中忘记了一件事:我忘了在 all_cols= 行上方添加行 X=trainDF
  • 我发现了错误并更正了代码。现在请告诉我这是否能解决您的问题。

标签: python matplotlib scikit-learn pca


【解决方案1】:

您看到此错误的原因是 X_r2 仅包含一列(至少在您提供的数据的情况下)。但是,在命令 y=X_LDA_sklearn[:, 1][yf==i] 中,您尝试访问第二列,因此会引发您观察到的错误。

我在您提供的示例数据中添加了第三个类(使用两个类,降维不是那么合理),并将您的数据帧转换为数组。它现在运行良好并产生以下图表(由于数据量少,信息量不大):

这是更新后的代码:

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import csv

from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

trainDF = pd.DataFrame({'Out': [1, 0, 0, 0, 1, 3, 3],
                        'Revolver': [0.766, 0.957, 0.658, 0.233, 0.907, 0.1, 0.15],
                        'Ratio': [0.803, 0.121, 0.085, 0.036, 0.024, 0.6, 0.8],
                        'Num': [0, 1, 0, 3, 5, 4, 4]})
#drop NA values
trainDF = trainDF.dropna()

trainDF['Num'].loc[(trainDF['Num']==8) | (trainDF['Num']==17)] = trainDF['Num'].median()

# convert dataframe to numpy array
y = trainDF['Out'].as_matrix()

# convert dataframe to numpy array
X = trainDF.drop('Out', 1).as_matrix()

target_names = ['out', 'in']

pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
      % str(pca.explained_variance_ratio_))

plt.figure()
for c, i, target_name in zip("rgb", [0, 1], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], c=c, label=target_name)
plt.legend()
plt.title('PCA of Out')

plt.figure()
for c, i, target_name in zip("rgb", [0, 1], target_names):
    plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], c=c, label=target_name)
plt.legend()
plt.title('LDA of Out')

plt.show()

因此,当您遇到这些“索引超出范围”错误时,请务必先检查数组的尺寸。

【讨论】:

  • 非常感谢您的帮助。我只有一个担心。我非常重视我的隐私,所以如果您可以将target_names 更改为不同的名称,例如[out,in],并将plt.title 更改为plt.title('PCA of Out'),我将不胜感激。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 2016-08-25
  • 2013-12-16
  • 2017-04-05
  • 2014-08-01
  • 2023-03-10
相关资源
最近更新 更多