为什么在代码中找不到'example_size'?

why 'example_size' can't be found in the code?

import  numpy as np

def data_iter_random(data_indices, num_steps, batch_size):
    example_size = len(data_indices)/num_steps
    epoch_size = example_size/batch_size
    example = [data_indices[i*num_steps:i*num_steps + num_steps] 
              for i in range(int(example_size))]
    shuffle_example = np.random.shuffle(example)
    print(shuffle_example)


data_iter_random(list(range(30)), 5, 2)

输出为None

谁能告诉我哪里出了问题?

问题是 np.random.shuffle 就地修改了序列。来自 documentation:

Modify a sequence in-place by shuffling its contents.

只需打印 example:

import numpy as np


def data_iter_random(data_indices, num_steps, batch_size):
    example_size = len(data_indices) / num_steps
    epoch_size = example_size / batch_size
    example = [data_indices[i * num_steps:i * num_steps + num_steps]
               for i in range(int(example_size))]
    np.random.shuffle(example)
    print(example)


data_iter_random(list(range(30)), 5, 2)

输出

[[25, 26, 27, 28, 29], [5, 6, 7, 8, 9], [0, 1, 2, 3, 4], [20, 21, 22, 23, 24], [15, 16, 17, 18, 19], [10, 11, 12, 13, 14]]

因为np.random.shuffle是一个"in-place"方法。

  • 所以不需要赋值

  • 是否就地

  • 文档说:"Modify a sequence in-place by shuffling its contents."

也一样:

np.random.shuffle(example)
print(example)

对于那些行。

完整代码:

import  numpy as np

def data_iter_random(data_indices, num_steps, batch_size):
    example_size = len(data_indices)/num_steps
    epoch_size = example_size/batch_size
    example = [data_indices[i*num_steps:i*num_steps + num_steps] 
              for i in range(int(example_size))]
    np.random.shuffle(example)
    print(example)


data_iter_random(list(range(30)), 5, 2)

输出:

[[5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [25, 26, 27, 28, 29], [15, 16, 17, 18, 19], [0, 1, 2, 3, 4], [20, 21, 22, 23, 24]]

很少有这样的功能。