numpy.random.shuffle打乱顺序函数的实现

yipeiwu_com6年前Python基础

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python paramiko模块学习分享

paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。paramiko支持Linux, Solaris, BSD, MacOS...

Python MD5文件生成码

import md5 import sys def sumfile(fobj): m = md5.new() while True: d = fobj.read(8096) if not...

Python实现Windows和Linux之间互相传输文件(文件夹)的方法

Python实现Windows和Linux之间互相传输文件(文件夹)的方法

项目中需要从Windows系统传输ISO文件到Linux测试系统,然后再Linux测试系统里安装这个ISO文件。所以就需要实现如何把文件从Windows系统传输到Linux系统中。 在项...

利用Python绘制MySQL数据图实现数据可视化

利用Python绘制MySQL数据图实现数据可视化

本教程的所有Python代码可以在网上的IPython notebook中获取。 考虑在公司里使用Plotly?可以看一下Plotly的on-premises企业版。(注:On-prem...

在python中做正态性检验示例

利用观测数据判断总体是否服从正态分布的检验称为正态性检验,它是统计判决中重要的一种特殊的拟合优度假设检验。 直方图初判 :直方图 + 密度线 QQ图判断:(s_r.index - 0.5...