0

I was trying to fit different cross_val_score type(k-fold(),LeaveOneOut(),LeavepOut()) in iris dataset of sklearn.But LeaveOneOut() leads to nan score list.why is this happening?Can anyone explain?Let me attach my part of code here==>

kfindex=LeaveOneOut()
model=LinearRegression()
scores=cross_val_score(model,iris.data,iris.target,cv=kfindex)
print(scores.mean(),scores.shape,scores)

output==>(score) [nan (150,) [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan]]

I tried cross_val_score manualy.it also lead to the same output

i=0
scores=[]
for train_x_indices,test_x_indeces in kfindex.split(iris.data):
    xtrain,xtest=iris.data[train_x_indices],iris.data[test_x_indices]
    ytrain,ytest=iris.target[train_x_indices],iris.target[test_x_indices]
#     print(xtrain.shape)
    i+=1

    model.fit(xtrain,ytrain)
    a=model.score(xtest,ytest)
    scores.append(a)
print(i)
print(scores,np.mean(scores))

There are somany questions relating this nan value of cross_val_score.But none of them are leading to my solution.Please someone help

1 Answers1

-1

The correct way to implement Cross Validation using LeaveOneOut() is as below for iris dataset:

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import LeaveOneOut

iris = load_iris() # Load the iris dataset

x = iris.data
y = iris.target
cv = LeaveOneOut()

y_true, y_pred = [], []

for train_ix, test_ix in cv.split(x):
    train_x, test_x = x[train_ix, :], x[test_ix, :]
    train_y, test_y = y[train_ix], y[test_ix]
    lr = LogisticRegression(solver='newton-cg')
    lr.fit(train_x, train_y)

    predicted_y = lr.predict(test_x)

    y_true.append(test_y[0])
    y_pred.append(predicted_y[0])

print(f"Accuracy Score of Logistic Regression model is {round(accuracy_score(y_true, y_pred), 2)}")
Praneeth
  • 7
  • 5
  • Thankz for the code..if you don't mind can you explain where the code get wrong?and how can we correct the code of cross_val_score class? – Shilpa Ajith Jun 23 '23 at 07:44