Python for loop从2个数据集中获取n行数据。

问题描述 投票:0回答:1

我想每次使用zip()从x_train和y_train的for循环中获取n行。所以下面的代码是我尝试做的,在每次迭代时,我更新上一批次和下一批次,所以我将得到[0-5],[5-10],......行从两个2d numpy数组。

batch_size = 3
next_b = batch_size
prev_b = 0

//sample input
x_train = [ [0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14] ]
y_train = [ [3],[6],[9],[12],[15] ]    

for X,y in zip(x_train,y_train)[prev_b:next_b]:
    print(X,y)

    //prev_b = 0, next_b = 3, so i want to get below values at first iter
    //X => [[0,1,2],[3,4,5],[6,7,8]]
    //y => [ [3],[6],[9] ]

    prev_b = next_b //-> prev_b = 3, for the next iteration
    next_b += batch_size //-> next_b = 6, for the next iteration

任何帮助是欢迎的。

python-3.x numpy-ndarray python-zip
1个回答
0
投票

在这里,你可以用正确定义的索引来切分你的列表。

x_train = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
y_train = [[3], [6], [9], [12], [15]]
batch_size = 3

for loop_number, start in enumerate(range(0, len(x_train), batch_size)):
    print(f"loop {loop_number}")
    end = start + batch_size
    X = x_train[start:end]
    y = y_train[start:end]
    print(f"X equals {X}")
    print(f"y equals {y}\n")

结果:

loop 0
X equals [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
y equals [[3], [6], [9]]

loop 1
X equals [[9, 10, 11], [12, 13, 14]]
y equals [[12], [15]]
© www.soinside.com 2019 - 2024. All rights reserved.