【问题标题】:why 'example_size' can't be found in the code?为什么在代码中找不到“example_size”?
【发布时间】:2018-10-24 02:54:38
【问题描述】:
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

谁能告诉我怎么了?

【问题讨论】:

  • 标题可能需要更改,因为这太具体了

标签: python numpy shuffle


【解决方案1】:

问题在于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]]

【讨论】:

    【解决方案2】:

    这是因为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]]
    

    这样的功能很少。

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 1970-01-01
      • 2020-01-07
      • 2019-09-17
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      相关资源
      最近更新 更多