如何更正IndexError

时间:2019-03-22 03:06:06

标签: python scikit-learn

使用Python Scikit-learn实现的Logistic回归算法,根据花瓣的长度和宽度对鸢尾花数据集中的三种花朵(Setosa,Versicolor,Virgin)进行分类。

我可以知道如何更正编码,请参见附件-

from sklearn import datasets

#load data
iris=datasets.load_iris()
X=iris.data[:,[2,3]]
y=iris.target
from sklearn.model_selection import train_test_split
X_train, X_test,y_train, y_test=train_test_split(X,y,test_size=0.3, random_state=0,stratify=y)
#feature scaling
from sklearn.preprocessing import StandardScaler
sc=StandardScaler()
sc.fit(X_train)
X_train_std=sc.transform(X_train)
X_test_std=sc.transform(X_test)
#Logistic regression
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
C1=[]
A=[]
C1=[0.01,0.1,1,10,100,1000]
for i in range(len(C1)):
    lr=LogisticRegression(C=C1[i], random_state=0)
    lr.fit(X_train_std,y_train)
    y_pred=lr.predict(X_test_std)
    A[i].append(accuracy_score(y_test,y_pred))

#draw figure
import matplotlib.pyplot as plt
plt.plot(C1,A)
plt.title('Logistic Regression')
plt.xlabel('C')
plt.ylabel('Accuracy')
plt.show()

请查看图片-enter image description here     

这是错误-

runfile('C:/Users/HSIPL/Desktop/testttttttttttttttttt.py', wdir='C:/Users/HSIPL/Desktop')
Reloaded modules: __mp_main__
Traceback (most recent call last):

  File "<ipython-input-4-94a347d3dde0>", line 1, in <module>
    runfile('C:/Users/HSIPL/Desktop/testttttttttttttttttt.py', wdir='C:/Users/HSIPL/Desktop')

  File "C:\Users\HSIPL\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
    execfile(filename, namespace)

  File "C:\Users\HSIPL\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/HSIPL/Desktop/testttttttttttttttttt.py", line 26, in <module>
    A[i].append(accuracy_score(y_test,y_pred))

IndexError: list index out of range

2 个答案:

答案 0 :(得分:2)

通过执行A[i].append(accuracy_score(y_test,y_pred)),您是说A本身包含lists,并试图为每个分数附加一个分数。

但是,A是一个空的list,因此您只想要A.append(accuracy_score(y_test,y_pred))

答案 1 :(得分:0)

主要:问题在import random print('Please rearrange the following numbers in ascending order') strain = [] for i in range(6): strain.append(random.randint(1,100)) print(strain) sortedstrain = sorted(strain) Answer = [int(x) for x in input('Answer Here: ').split()] if Answer == sortedstrain: print('correct') else: print('wrong') 附近,您无需执行train_test_split(X,y,test_size=0.3, random_state=0)

其他:您需要将比例尺更改为stratified sampling。和log代替A.append

A[i].append