版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huanghaocs/article/details/83242353
参考此文:https://blog.csdn.net/qq_33039859/article/details/79901667
产生batch数据
输入data中每个样本可以有多个特征,和一个标签,最好都是numpy.array格式。
datas = [data1, data2, …, dataN ], labels = [label1, label2, …, labelN],
其中data[i] = [feature1, feature2,…featureM], 表示每个样本数据有M个特征。
输入我们方法的数据,all_data = [datas, labels] 。
代码实现
通过索引值来产生batch大小的数据,同时提供是否打乱顺序的选择,根据随机产生数据量范围类的索引值来打乱顺序。
import numpy as np
def batch_generator(all_data , batch_size, shuffle=True):
"""
:param all_data : all_data整个数据集
:param batch_size: batch_size表示每个batch的大小
:param shuffle: 每次是否打乱顺序
:return:
"""
all_data = [np.array(d) for d in all_data]
data_size = all_data[0].shape[0]
print("data_size: ", data_size)
if shuffle:
p = np.random.permutation(data_size)
all_data = [d[p] for d in all_data]
batch_count = 0
while True:
if batch_count * batch_size + batch_size > data_size:
batch_count = 0
if shuffle:
p = np.random.permutation(data_size)
all_data = [d[p] for d in all_data]
start = batch_count * batch_size
end = start + batch_size
batch_count += 1
yield [d[start: end] for d in all_data]
测试数据
样本数据x和标签y可以分开输入,也可以同时输入。
# 输入x表示有23个样本,每个样本有两个特征
# 输出y表示有23个标签,每个标签取值为0或1
x = np.random.random(size=[23, 2])
y = np.random.randint(2, size=[23,1])
batch_size = 5
batch_gen = batch_generator([x, y], batch_size)
for i in range(20):
batch_x, batch_y = next(batch_gen)
print(batch_x, batch_y)