I was implementing 10-fold cross validation from scratch in Python. The language is Python 3.6 and I wrote this in Spyder (Anaconda). My input shape is 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.
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.append(X[j:j+143,:])
Similarly for foldy
foldy.append(y[foldx[j]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.