1. 程式人生 > >python numpy array random 隨機排列(打亂訓練資料)

python numpy array random 隨機排列(打亂訓練資料)

對numpy.array重新排列:

  • numpy.random.shuffle(x):修改本身,打亂順序
import numpy as np
arr = np.array(range(0, 21, 2))
np.random.shuffle(arr)
arr 	#打亂順序後的陣列, 如[2, 6, 4, 8, 12, 16, 0, 18, 10, 14, 20]

arr = np.array(range(12)).reshape(3, 4)
np.random.shuffle(arr)
arr		# 預設對第一維打亂,[[3, 4, 5], [0, 1, 2], [9, 10, 11], [6, 7, 8]]
  • numpy.random.permutation(x):返回一個隨機排列
arr = np.array(range(0, 21, 2))
r = np.random.permutation(arr)
r 		#打亂的索引序列,如[2, 6, 4, 8, 12, 16, 0, 18, 10, 14, 20]

arr = np.array(range(12)).reshape(3, 4)
r = np.random.permutation(arr)
arr		# 預設對第一維打亂,如[[3, 4, 5], [0, 1, 2], [9, 10, 11], [6, 7, 8]]

對訓練集打亂

# train_X:3列, train_y
per = np.random.permutation(train_X.shape[0]) #打亂後的行號 new_train_X = train_X[per, :, :] #獲取打亂後的訓練資料 new_train_y = trainy[per]