Reference link https://blog.csdn.net/weixin_44633882/article/details/103748747
Python randomly select n elements in list or numpy.ndarray
1. Randomly select an element from a list
- random.choice(data)
import random
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
random.choice(data) # 随机选取一个元素
2. Randomly select multiple elements from a list
import random
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
sample_num = 5
random.sample(data, sample_num) # 结果['a', 'd', 'b', 'f', 'c'],每次运行结果不同。
3. Randomly select multiple elements from data and label
When making a data set, there may be a requirement to use only 50% of the data. Therefore, we randomly sample 30% of the data from the original data set. This is also required, data
and label
is corresponding. Next, talk about my approach. Create an index list, select N indexes in the index list, and extract the data and label data according to these indexes.
import random
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
label = [0, 1, 2, 3, 4, 5, 6, 7]
sample_num = int(0.5 * len(data)) # 假设取50%的数据
sample_list = [i for i in range(len(data))] # [0, 1, 2, 3, 4, 5, 6, 7]
sample_list = random.sample(sample_list, sample_num) #随机选取出了 [3, 4, 2, 0]
sample_data = [data[i] for i in sample_list] # ['d', 'e', 'c', 'a']
sample_label = [label[i] for i in label] # [3, 4, 2, 0]
4. Randomly select multiple elements from numpy.ndarray
3. undertake only data
and label
is numpy.ndarray
subject How sample_list
to remove it? Those of you who
know numpy.ndarray
slices must all know it. Here I will write briefly.
import numpy as np
data = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]]) # shape:(4,4)
label = np.array([1,2,3,4]) # shape:(4,)
sample_num = int(0.5 * len(data)) # 假设取50%的数据
sample_list = [i for i in range(len(data))] # [0, 1, 2, 3]
sample_list = random.sample(sample_list, sample_num) # [1, 2]
data = data[sample_list,:] # array([[ 4, 5, 6, 7], [ 8, 9, 10, 11]])
label = label[sample_list] # array([2, 3])