Python NumPy 随机数据打乱:随机排列数组元素
import numpy as np
# 设置随机数种子
np.random.seed(0)
# 假设 df6 和 labels 是已有的数组
df6 = np.array(df6)
n = df6.shape[0]
labels = np.array(labels)
labels = (labels >= 2).astype(int)
# 生成随机排列的索引
rand_index = np.random.permutation(n)
# 根据随机索引打乱数组元素
df6 = df6[rand_index]
labels = labels[rand_index]
本代码使用 np.random.seed(0) 设置随机数种子,确保每次运行代码时都能得到相同的随机排列结果。np.random.permutation(n) 函数生成一个从 0 到 n-1 的随机排列索引,然后使用该索引对 df6 和 labels 数组进行索引,从而实现随机打乱数据。
例如,如果 df6 和 labels 数组分别包含 5 个元素,则 rand_index 可能是一个随机排列的索引数组,例如 [2, 0, 4, 1, 3]。使用该索引对 df6 和 labels 进行索引后,它们的元素将被重新排列,并得到随机打乱的结果。
注意:
- 随机数种子只在每次运行代码时生效。如果需要每次运行代码时都得到不同的随机排列结果,可以删除
np.random.seed(0)代码。 - 随机排列通常用于机器学习中对训练数据进行打乱,以防止模型过度拟合。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ooDM 著作权归作者所有。请勿转载和采集!