我正在尝试通过逻辑回归解决一个给定数据集的分类问题(这不是问题所在)。为了避免过拟合,我尝试通过交叉验证来实现(问题就在这里):我似乎遗漏了一些东西,无法完成程序。我的目的是确定准确率。
让我具体说明一下。我所做的如下:
- 将数据集分为训练集和测试集
- 定义要使用的逻辑回归预测模型
- 使用cross_val_predict方法(在sklearn.cross_validation中)进行预测
- 最后,测量准确率
这是代码:
import pandas as pdimport numpy as npimport seaborn as snsfrom sklearn.cross_validation import train_test_splitfrom sklearn import metrics, cross_validationfrom sklearn.linear_model import LogisticRegression # read training data in pandas dataframedata = pd.read_csv("./dataset.csv", delimiter=';')# last column is target, store in array tt = data['TARGET']# list of features, including targetfeatures = data.columns# item feature matrix in XX = data[features[:-1]].as_matrix()# remove first column because it is not necessary in the analysisX = np.delete(X,0,axis=1)# divide in training and test setX_train, X_test, t_train, t_test = train_test_split(X, t, test_size=0.2, random_state=0)# define methodlogreg=LogisticRegression()# cross valitadion predictionpredicted = cross_validation.cross_val_predict(logreg, X_train, t_train, cv=10)print(metrics.accuracy_score(t_train, predicted))
我的问题:
-
据我所知,测试集应该在最后才考虑,而交叉验证应该在训练集上进行。这就是为什么我在cross_val_predict方法中使用了X_train和t_train。然而,我得到一个错误提示:
ValueError: Found input variables with inconsistent numbers of samples: [6016, 4812]
其中6016是整个数据集中的样本数,而4812是数据集分割后训练集中的样本数
-
在此之后,我不知道该怎么做。我的意思是:X_test和t_test什么时候派上用场?我不知道在交叉验证之后如何使用它们,以及如何获得最终的准确率。
额外问题:我还想在交叉验证的每个步骤中执行缩放和降维(通过特征选择或PCA)。我该如何做到这一点?我看到定义一个管道可以帮助进行缩放,但我不知道如何将此应用于第二个问题。
回答:
这是在一个样本数据框上测试过的工作代码。您的代码中第一个问题是目标数组不是np.array。您也不应该在特征中包含目标数据。下面我展示了如何使用train_test_split手动分割训练和测试数据。我还展示了如何使用包装器cross_val_score自动分割、拟合和评分。
random.seed(42)# Create example df with alphabetic col names.alphabet_cols = list(string.ascii_uppercase)[:26]df = pd.DataFrame(np.random.randint(1000, size=(1000, 26)), columns=alphabet_cols)df['Target'] = df['A']df.drop(['A'], axis=1, inplace=True)print(df.head())y = df.Target.values # df['Target'] is not an np.array.feature_cols = [i for i in list(df.columns) if i != 'Target']X = df.ix[:, feature_cols].as_matrix()# Illustrated here for manual splitting of training and testing data.X_train, X_test, y_train, y_test = \ model_selection.train_test_split(X, y, test_size=0.2, random_state=0)# Initialize model.logreg = linear_model.LinearRegression()# Use cross_val_score to automatically split, fit, and score.scores = model_selection.cross_val_score(logreg, X, y, cv=10)print(scores)print('average score: {}'.format(scores.mean()))
输出
B C D E F G H I J K ... Target0 20 33 451 0 420 657 954 156 200 935 ... 2531 427 533 801 183 894 822 303 623 455 668 ... 4212 148 681 339 450 376 482 834 90 82 684 ... 9033 289 612 472 105 515 845 752 389 532 306 ... 6394 556 103 132 823 149 974 161 632 153 782 ... 347[5 rows x 26 columns][-0.0367 -0.0874 -0.0094 -0.0469 -0.0279 -0.0694 -0.1002 -0.0399 0.0328 -0.0409]average score: -0.04258093018969249
有用的参考资料: