如何将文档拆分为训练集和测试集?


圈圈红
2025-03-15 06:24:29 (24天前)
  1. 我正在尝试建立一个分类模型。我在本地文件夹中有1000个文本文档。我想把它们分成两部分


训练
</跨度>
设置和

测试
</跨度>
设定分裂比为70:30(70->

训练
</跨度>
和30 - &gt;

测试
</跨度>
倒是这个问题。虽然我得到了近乎完美的答案,但我还想简要提问。

我想以编程方式分割方法

训练
</跨度>
设置和

测试
</跨度>
组。首先阅读 中的文件

4 条回复
  1. 0# 妖邪 | 2019-08-31 10-32



    您可以使用sklearn提供的train_test_split方法。请参阅此处的文档




    http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html


  2. 1# v-star*위위 | 2019-08-31 10-32



    只需使用即可创建文件名列表

    os.listdir()

    。使用

    collections.shuffle()

    洗牌,然后

    training_files = filenames[:700]



    testing_files = filenames[700:]


  3. 2# 荧惑 | 2019-08-31 10-32



    如果你使用numpy,这很简单,首先加载文档并使它们成为一个numpy数组,然后:




    1. import numpy as np

    2. docs = np.array([
      one’, two’, three’, four’, five’,
      six’, seven’, eight’, nine’, ten’,
      ])

    3. idx = np.hstack((np.ones(7), np.zeros(3))) # generate indices
      np.random.shuffle(idx) # shuffle to make training data and test data random

    4. train = docs[idx == 1]
      test = docs[idx == 0]

    5. print(train)
      print(test)

    6. </code>


    结果:




    1. [‘one two three six eight nine ten’]
      [‘four five seven’]

    2. </code>

登录 后才能参与评论