python/numpy随机选取训练集/测试集索引
生活随笔
收集整理的這篇文章主要介紹了
python/numpy随机选取训练集/测试集索引
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在訓練模型中, 往往需要對數據集進行處理,從數據集中隨機選取部分數據作為訓練集,而另一部分數據作為測試集,一個常用的方法是隨機選取索引,下面介紹兩種從0~n中隨機選取x個不重復索引的方法。
注意下述兩種方法選出來的都是整數。
方法一、用python的random
import random def getRandomIndex(n, x):# 索引范圍為[0, n), 隨機選x個不重復index = random.sample(range(n), x)return index方法二、用numpy.random.choice
import numpy as np def getRandomIndex(n, x):# 索引范圍為[0, n),隨機選x個不重復,注意replace=False才是不重復,replace=True則有可能重復index = np.random.choice(np.arange(n), size=x, replace=False)return index那么到這兒已經獲取到測試集的索引了,那么得將其余的索引單獨做一個數組作為訓練集的索引,做法如下
import numpy as np # 先根據上面的函數獲取test_index test_index = np.array(getRandomIndex(n, x)) # 再講test_index從總的index中減去就得到了train_index train_index = np.delete(np.arange(n), test_index)總結
以上是生活随笔為你收集整理的python/numpy随机选取训练集/测试集索引的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux进程详解
- 下一篇: python库numpy使用技巧(二)—