【问题标题】:How to shuffle two numpy arrays, so that record indices are stay aligned in both after shuffling?如何洗牌两个numpy数组,以便在洗牌后记录索引在两者中保持对齐?
【发布时间】:2021-08-11 14:49:30
【问题描述】:

我有一个 4D 数组和一个 1D 数组:

import numpy as np

data = np.random.randn(10, 1, 5, 5)    # num_records, depth, height, width
labels = np.array([1,1,1,1,1,0,0,0,0,0])

我想按num_records 打乱数据和标签,以随机顺序获得labels

我知道可以使用shuffle 函数:np.random.shuffle(data)。但是我不知道如何在洗牌后保持datalabels之间的关系。

【问题讨论】:

    标签: python arrays numpy shuffle


    【解决方案1】:

    这会将两个数组混在一起:

    import numpy as np
    
    data = np.random.randn(10, 1, 5, 5)    # num_records, depth, height, width
    labels = np.array([1,1,1,1,1,0,0,0,0,0])
    
    # shuffle indices
    idx = np.random.permutation(range(len(labels)))
    
    # shuffle together
    data, labels = data[idx,:,:,:], labels[idx]
    

    【讨论】:

    • 你不需要在 numpy 中使用尾随冒号。 data, labels = data[idx], labels[idx] 会做同样的事情
    【解决方案2】:
    import sklearn.utils as sku
    array1_shuffled, array2_shuffled = sku.shuffle(array1, array2)
    

    https://www.kite.com/python/answers/how-to-shuffle-two-numpy-arrays-in-unision-in-python

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多