python-3.x - Python for 循环从 2 个数据集中获取 n 行
问题描述
我想每次使用 zip() 从 x_train 和 y_train 中获取 n 行。所以下面的代码是我试图做的。在每次迭代中,我更新上一个批次和下一个批次,所以我将从两个 2d numpy 数组中获得 [0-5],[5-10],... 行。
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
欢迎任何帮助。
解决方案
在这里,只需使用正确定义的索引对列表进行切片:
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]]
推荐阅读
- r - 不同的行数
- java - 2021 年远程调试 GWT 2.4
- python - 如何将目录结构的树状输出转换为 JSON
- node.js - Mongodb查询不到指定时间
- c - 为什么我可以在 C 中定义一个变量两次?
- elasticsearch - 为什么ES中不推荐search_after中使用的_id
- system-calls - RISC-V (RV32I) - SCALL/ECALL、SBREAK/EBREAK、FENCE、FENCE.I
- google-sheets - 有没有更好的方法来嵌套 500 个 if 语句(Google 表格)?
- firebase - 为什么我的 StreamBuilder 只能在热重载后工作?
- ssl - 将 SSL 从 Winlogbeat 配置到 Elasticsearch