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

时间:2018-10-24 02:54:39

标签: python numpy shuffle

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

谁能告诉我出什么问题了?

2 个答案:

答案 0 :(得分:0)

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

  

通过改组其内容就地修改序列。

仅打印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]]

答案 1 :(得分:0)

这是因为np.random.shuffle是“就地”方法。

  • 因此无需分配

  • 就地完成

  • 医生说:“通过改组其内容就地修改序列。”

也是这样:

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]]

几乎没有这样的功能。

相关问题