前言
使用深度学习训练模型时,数据的随机分布非常重要,增加模型的泛型能力,防止过拟合!
shuffle()函数
在原有数据的基础上操作,打乱元素的顺序,无返回值
import numpy as np
arr = np.arange(10)
print(arr)
[0 1 2 3 4 5 6 7 8 9]
np.random.shuffle(arr)
print(arr)
[6 4 7 3 0 1 9 5 2 8]
arr = np.arange(9).reshape(3, 3)
print(arr)
[[0 1 2]
[3 4 5]
[6 7 8]]
np.random.shuffle(arr)
print(arr)
[[3 4 5]
[6 7 8]
[0 1 2]]
permutation()函数
不是在原有数据的基础上操作,而是返回一个新的打乱顺序的数组
arr = np.arange(10)
print(arr)
[0 1 2 3 4 5 6 7 8 9]
new_arr = np.random.permutation(arr)
print(new_arr)
[1 6 9 4 2 7 8 0 3 5]
print(arr)
[0 1 2 3 4 5 6 7 8 9]
# -------------------------------------
arr = np.arange(9).reshape(3, 3)
print(arr)
[[0 1 2]
[3 4 5]
[6 7 8]]
new_arr = np.random.permutation(arr)
print(new_arr)
[[3 4 5]
[0 1 2]
[6 7 8]]
模拟
下面我们使用permutation函数模拟一个随机打乱数据样本的一段代码:
# -*- coding: utf-8 -*-
"""
@Date: 2020/4/28 22:53
@Author: Pangpd
@FileName: testRandom.py
@IDE: PyCharm
@Description:
"""
import numpy as np
def random_unison(a, b, rstate=None):
assert len(a) == len(b) # 用于判断一个表达式,在表达式条件为false时触发异常。
p = np.random.RandomState(seed=rstate).permutation(len(a)) # 随机生成长度为len(a)的序列
return a[p], b[p]
data = np.arange(45).reshape(5, 3, 3) # 模拟数据
print("打乱前数据:", data)
print('----------') # 模拟标签
lables = np.array([4, 13, 22, 31, 40])
data, lables = random_unison(data, lables, rstate=1000)
print("打乱后数据:", data)
print("标签:", lables)
打乱前数据: [[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]
[[27 28 29]
[30 31 32]
[33 34 35]]
[[36 37 38]
[39 40 41]
[42 43 44]]]
---------------------------------
打乱后数据: [[[18 19 20]
[21 22 23]
[24 25 26]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[36 37 38]
[39 40 41]
[42 43 44]]
[[27 28 29]
[30 31 32]
[33 34 35]]]
标签: [22 13 4 40 31]
参考链接
https://blog.csdn.net/qifeidemumu/article/details/89000275
https://blog.csdn.net/weixin_41571493/article/details/80550076
https://www.zhihu.com/question/296155375(为什么打乱数据)