【问题标题】:Create training and test dataset in Pandas在 Pandas 中创建训练和测试数据集
【发布时间】:2015-07-16 03:41:53
【问题描述】:

我想在 pandas 中手动创建一个训练和测试数据集,而不是使用 sklearn 的交叉验证。我几乎成功了。但是,我发现 df_trainingdf_test 之间的数字存在差异。这是为什么?

这就是我所做的:

  • 通过使用 random.choice 随机选择行,从原始数据框中创建了一个名为 df_training 的新数据集
  • 通过使用 df.drop(df_training.index) 作为参数从原始数据集中删除 df_training 中的行创建了一个名为 df_test 的新数据集。

当 df 和 df_training 的尺寸保持不变时,我没有得到 df_test 的校正尺寸。

from sklearn.datasets import load_boston 
boston = load_boston()

names = ['crim', 'zn', 'indus', 'chas', 'nox', 'rm', 'age', 'dis', 'rad', 'tax', 'ptratio', 'b', 'lstat']
df = pd.DataFrame(boston.data, columns=names)
# add in prices
df['price'] = boston.target

df.shape
(506, 14)

import random
# Use 70% of the DataFrame and call is df_training
df_training = df.ix[np.random.choice(df.index, 354)]
df_training.shape

# Remove the 70% of data from the main DataFrame and call it df_test
df_test = df.drop(df_training.index)

df_test.shape
(250, 14)

我不应该得到 504 - 354 = 150 吗?

有趣的是,当我多次运行整个代码时,我得到了 test_set 的不同结果。当训练集和原始集不变时,我不应该得到相同的结果吗?这是怎么回事?

In [26]: %run create_training.py
Original Set:  (506, 14)
training set:  (354, 14)
test set:  (247, 14)

In [27]: %run create_training.py
Original Set:  (506, 14)
training set:  (354, 14)
test set:  (254, 14)

In [28]: %run create_training.py
Original Set:  (506, 14)
training set:  (354, 14)
test set:  (241, 14)

【问题讨论】:

标签: numpy pandas


【解决方案1】:

我认为这里缺少的两个要素是:

  • numpy 随机函数设置种子,以使拆分可重现。
  • 使用replacement=Falserefer to the docs 了解更多信息)呼叫np.random.choice

代码:

# make results reproducible
np.random.seed(42)
# sample without replacement
train_ix = np.random.choice(df.index, 354, replace=False)
df_training = df.ix[train_ix]
df_test = df.drop(train_ix)

【讨论】:

  • 甜蜜!感谢您的所有帮助。
猜你喜欢
  • 2020-07-07
  • 1970-01-01
  • 2019-03-21
  • 2017-09-11
  • 2020-09-24
  • 2017-02-20
  • 2019-12-03
  • 1970-01-01
  • 2018-02-25
相关资源
最近更新 更多