1. 程式人生 > 程式設計 >numpy.random.shuffle打亂順序函式的實現

numpy.random.shuffle打亂順序函式的實現

numpy.random.shuffle

在做將caffe模型和預訓練的引數轉化為tensorflow的模型和預訓練的引數,以便微調,遇到如下函式:

def gen_data(source):
  while True:
    indices = range(len(source.images)) # indices = the number of images in the source data set
    random.shuffle(indices)
    for i in indices:
      image = np.reshape(source.images[i],(28,28,1))
      label = source.labels[i]
      yield image,label

之前卑鄙陋寡聞,不知道這個用法,按照字面上的意思是打亂,那麼這裡就應該是讓訓練資料集中的資料打亂順序,然後一個挨著一個地(for i in indices)生成訓練資料對。下面就從docs.scipy.org中查到的random.shuffle的用法:

numpy.random.shuffle(x)

Modify a sequence in-place by shuffling its contents.

Parameters:

x : array_like

The array or list to be shuffled.

Returns:

None

舉例

python>>>
>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8]

This function only shuffles the array along the first index of a multi-dimensional array(多維矩陣中,只對第一維(行)做打亂順序操作):

python>>>
>>> arr = np.arange(9).reshape((3,3))
>>> np.random.shuffle(arr)
>>> arr
array([[3,4,5],[6,7,8],[0,1,2]])This function only shuffles the array along the first index of a multi-dimensional array:

參考:

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html#numpy-random-shuffle

[2]https://github.com/ethereon/caffe-tensorflow/blob/master/examples/mnist/finetune_mnist.py

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。