,y_train,y_test = model_selection.train_test_split(X,y,test_size = 0.4)
问题:如果我想要哪些样品的名称在 测试 </跨度> / 训练 </跨度> 数据(测试后),如何检索它们? 具有分类(X)和隔离分类列(y)的列X = np.array(df.drop([‘class’],1))y = np.array(df [‘class’])
######
训练 </跨度> 数据集X_train,X_test
如果你做 id 的指数 df ,你将在运行后保留索引值 train_test_split 。 首先,让我们生成一些示例数据:
id
df
train_test_split
import numpy as np import pandas as pd N = 10 ids = ['a','b','c','d','e','f','g','h','i','j'] values = np.random.random(N) classes = np.random.binomial(n=1,p=.5,size=N) df = pd.DataFrame({'id':ids,'predictor':values,'label':classes})
然后明确设置 id 作为索引:
df.set_index('id', inplace=True)
现在 df 看起来像这样:
label predictor id a 1 0.214636 b 0 0.466477 c 1 0.300480 d 1 0.378645 e 0 0.755834 f 1 0.506719 g 0 0.948360 h 0 0.736498 i 1 0.058591 j 1 0.997003
使用Pandas对象拆分到训练/测试集将保留其原始索引值:
X = df.predictor y = df.label from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4) print(X_train) id a 0.214636 b 0.466477 d 0.378645 j 0.997003 i 0.058591 f 0.506719 Name: predictor, dtype: float64