【问题标题】:Split randomly two lists in python in the same way以相同的方式在python中随机拆分两个列表
【发布时间】:2018-12-07 00:53:44
【问题描述】:

我有两个包含相同大小的 numpy 数组的列表。列表 list_A 有 1000 个项目,其中每个 numpy 数组的大小为 20x20x3list_B numpy 数组的大小为 20x8。我想以相同的方式将两个列表随机拆分为 100 个子列表(最后,list_A 的每个 sub_list 包含 100 个 numpy 数组,list_B 相同)。我只为一个列表编写了如何执行此操作的代码:

def partition (list_in, n):
    random.shuffle(list_in)
    return [list_in[i::n] for i in range(n)]

total_lists_A = partition (list_A, 10)

但是,我想以相同的方式对list_Alist_B 执行相同的操作并返回total_lists_Atotal_lists_B

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您可以在您的函数中包装numpy.random.seed,以使其可重现。类似于(根据您的方法):

    # note: will not work properly if your two lists are different shapes:
    def my_partition(list_in, n):
        np.random.seed(1)
        idx = np.random.shuffle(list_in)
        return [list_in[i::n] for i in range(n)]
    

    或者(稍微不同的方法,应该可以)

    def my_partition(list_in, n):
        np.random.seed(1)
        idx = np.random.choice(range(len(list_in)), len(list_in))
        split = np.split(idx, n)
        return [list_in[i] for i in split]
    

    【讨论】:

    • 如果第二个列表只是一个大小为 1000x20x8 的 numpy 数组,这样做是否容易?
    • 相信我的第二种方法应该这样做,只要两个数组中的第一个维度相同 (1000)
    • 列表大小不能被10整除的时候好像不行。可能是比如1003吧。
    • 在这种情况下,我收到错误消息:'数组拆分不会导致等分'
    • 如果它不能被 n 整除,你会怎么做?如果要使您的子数组大小接近相等(如果可能,则相等),请将np.split 替换为np.array_split
    【解决方案2】:

    我假设您这样做是为了机器学习。查看train_test_split

    如果您希望从头开始执行此操作,您可以首先生成一个长度数据向量 (np.arange),然后对其进行置换并将其用作您的索引(将置换后的索引拆分为训练集和测试集)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2020-03-14
      • 2022-01-04
      • 2019-01-02
      • 2011-05-28
      相关资源
      最近更新 更多