-2

大家好,我正在尝试对此保险数据集执行 K 折交叉验证,但我尝试使用 for 循环来迭代整数数组。输出给我以下错误:

ValueError: The number of folds must be of Integral type. [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] of type <class 'list'> was passed.

有人可以解释一下这个错误是什么以及如何解决它。下面是我的 K 折交叉验证代码。

import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import VarianceThreshold,mutual_info_classif,mutual_info_regression
from sklearn.feature_selection import SelectKBest, SelectPercentile

data_ = pd.read_csv("insurance.csv") 
print(data_.head())

# Create dummies

data_dummies= pd.get_dummies(data_, columns = ['sex','region','smoker'])
print(data_dummies.head())
data_dummies = pd.DataFrame(data_dummies)
data_cleaned = data_dummies.drop(['sex_female','region_southwest','smoker_no'],axis = 'columns')
X=  data_cleaned.drop(['charges'], axis = 'columns')
y = data_cleaned['charges']
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state = 0)

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
ind = [3,4,5,6,7,8,9,10,11,12]


for  i in ind:


     kfold = KFold(n_splits=ind,shuffle=True,random_state=0)
     model = LinearRegression()
     scores = cross_val_score(model,X,y,cv=kfold,scoring='neg_mean_squared_error')

print(scores)
4

1 回答 1

1

您在KFoldindn_splits参数中传递整个列表,而不是遍历它的 elements i,这是您的意图。另外,为什么要分配一个列表?你不想做吗

for i in range(3, 13):
    kfold = KFold(n_splits=i,shuffle=True,random_state=0)
    model = LinearRegression()
    scores = cross_val_score(model,X,y,cv=kfold,scoring='neg_mean_squared_error')
    print(scores)
于 2020-04-02T19:02:26.397 回答