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

yipeiwu_com5年前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设计】。

相关文章

Python3实现简单可学习的手写体识别(实例讲解)

Python3实现简单可学习的手写体识别(实例讲解)

1.前言 版本:Python3.6.1 + PyQt5 + SQL Server 2012 以前一直觉得,机器学习、手写体识别这种程序都是很高大上很难的,直到偶然看到了这个视频,听了老师...

python实现停车管理系统

Python停车管理系统可实现车辆入库,按车牌号或者车型查询车辆,修改车辆信息,车辆出库时实现计费,按车型统计车辆数和显示全部车辆信息的功能 (1)定义车辆类,属性有车牌号、颜色、车型(...

python中字典(Dictionary)用法实例详解

本文实例讲述了python中字典(Dictionary)用法。分享给大家供大家参考。具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的...

浅谈使用Python变量时要避免的3个错误

Python编程中经常遇到一些莫名其妙的错误, 其实这不是语言本身的问题, 而是我们忽略了语言本身的一些特性导致的,今天就来看下使用Python变量时导致的3个不可思议的错误, 以后在编...

Pytorch抽取网络层的Feature Map(Vgg)实例

这边我是需要得到图片在Vgg的5个block里relu后的Feature Map (其余网络只需要替换就可以了) 索引可以这样获得 vgg = models.vgg19(pretra...