我试图在python中重现R的createDataPartition函数的行为.我有一个用于机器学习的数据集,带有布尔目标变量.我想将我的数据集拆分为训练集(60%)和测试集(40%).
如果我完全随机,我的目标变量将不会在两组之间正确分配.
我用R实现它:
inTrain <- createDataPartition(y=data$repeater, p=0.6, list=F)
training <- data[inTrain,]
testing <- data[-inTrain,]
我怎样才能在Python中做同样的事情?
PS:我正在使用scikit-learn作为我的机器学习lib和python pandas.
解决方法:
在scikit-learn中,您可以获得工具train_test_split
from sklearn.cross_validation import train_test_split
from sklearn import datasets
# Use Age and Weight to predict a value for the food someone chooses
X_train, X_test, y_train, y_test = train_test_split(table['Age', 'Weight'],
table['Food Choice'],
test_size=0.25)
# Another example using the sklearn pre-loaded datasets:
iris = datasets.load_iris()
X_iris, y_iris = iris.data, iris.target
X, y = X_iris[:, :2], y_iris
X_train, X_test, y_train, y_test = train_test_split(X, y)
这会将数据分解为
分别.您还可以添加关键字参数:test_size = 0.25以更改用于培训和测试的数据百分比
要拆分单个数据集,您可以使用这样的调用来获得40%的测试数据:
>>> data = np.arange(700).reshape((100, 7))
>>> training, testing = train_test_split(data, test_size=0.4)
>>> print len(data)
100
>>> print len(training)
60
>>> print len(testing)
40
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。