简体   繁体   English

Python中10倍交叉验证代码中的错误

[英]Error in 10-fold cross validation code in Python

I was implementing 10-fold cross validation from scratch in Python. 我从头开始在Python中实现10倍交叉验证。 The language is Python 3.6 and I wrote this in Spyder (Anaconda). 语言是Python 3.6,我是在Spyder(Anaconda)中编写的。 My input shape is data=(1440,390),label=(1440,1). 我的输入形状是data =(1440,390),label =(1440,1)。

My code: 我的代码:

def partitions(X,y):
  np.random.shuffle(X)
  foldx=[]
  foldy=[]
  j=0
  for i in range(0,10):
    foldx[i]=X[j:j+143,:]
    foldy[i]=y[foldx[j]]
    j+=144
  return np.array(foldx),np.array(foldy)

def cv(X,y,model):
  trainx,trainy=partitions(X,y)
  scores=[]
  for i in range(0,10):
    xtest=trainx[i]
    ytest=trainy[xtest]
    xtrain=trainx[:i]+trainx[i+1:]
    ytrain=trainy[xtrain]
    model.fit(xtrain,ytrain)
    preds=model.predict(xtest)
    print(accuracy_score(np.ravel(ytest),preds))
    scores.append(accuracy_score(np.ravel(ytest),preds))
  return scores.mean()

The error comes at 错误出现在

foldx[i]=X[j:j+143,:]

where it says 它在哪里说

IndexError: list assignment index out of range. IndexError:列表分配索引超出范围。

How do I rectify this? 我该如何纠正? I am not very experienced in implementing such problems from scratch. 我对从头开始实施此类问题不是很有经验。

You have to first populate a list to use it's indices, change the foldx[i]=X[j:j+143,:] line to 您必须首先填充列表以使用其索引,然后将foldx[i]=X[j:j+143,:]行更改为

 foldx.append(X[j:j+143,:])

Similarly for foldy foldy

foldy.append(y[foldx[j]])

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

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