gpt4 book ai didi

python - 如何从 TFrecord 创建批处理用于 tensorflow 中的训练网络?

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:57 25 4
gpt4 key购买 nike

我已将数据保存到 tfrecord 文件中。它有 1000 个样本和 2 个特征(一个是输入,另一个是输出)。输入是形状 [1,20] 和输出 [1,10]。它们都是由扁平化的 numpy 数组创建的。我正在尝试从中创建批处理,以便我可以使用它们来训练我的网络,但我无法弄清楚如何进行。

这是我用于训练网络的代码

learning_rate = 0.01
epochs = 2
batch_size = 200 #total 5 batches
dataSize = 1000

dataset = rd.getData()

x = tf.placeholder(shape=(None,20), dtype=tf.float32)
y = tf.placeholder(shape=(None,10), dtype=tf.float32)

w1 = tf.Variable(tf.random_normal([20, 20], stddev=0.03))
w2 = tf.Variable(tf.random_normal([20, 20], stddev=0.03))
w3 = tf.Variable(tf.random_normal([20, 20], stddev=0.03))
w4 = tf.Variable(tf.random_normal([20, 20], stddev=0.03))
w5 = tf.Variable(tf.random_normal([20, 10], stddev=0.03))

b1 = tf.Variable(tf.random_normal([20]))
b2 = tf.Variable(tf.random_normal([20]))
b3 = tf.Variable(tf.random_normal([20]))
b4 = tf.Variable(tf.random_normal([20]))
b5 = tf.Variable(tf.random_normal([10]))

out1 = tf.add(tf.matmul(x, w1), b1)
out1 = tf.tanh(out1)

out2 = tf.add(tf.matmul(out1, w2), b2)
out2 = tf.tanh(out2)

out3 = tf.add(tf.matmul(out2, w3), b3)
out3 = tf.tanh(out3)

out4 = tf.add(tf.matmul(out3, w4), b4)
out4 = tf.tanh(out4)

out5 = tf.add(tf.matmul(out4, w5), b5)
finalOut = tf.tanh(out5)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=finalOut))


optimiser = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost)

# finally setup the initialisation operator
init_op = tf.global_variables_initializer()


with tf.Session() as sess:
# initialise the variables
sess.run(init_op)
total_batch = int(dataSize / batch_size)
for epoch in range(epochs):

iterator = dataset.make_one_shot_iterator()
avg_cost = 0

for i in range(total_batch):

#create batch
batch_y = []
batch_x = []
for counter in range(0,batch_size):
uv, z = iterator.get_next()
batch_x.append(uv)
batch_y.append(z)

_, c = sess.run([optimiser, cost],
feed_dict={x: batch_x, y: batch_y})
avg_cost += c / total_batch
print("Epoch:", (epoch + 1), "cost =", "{:.3f}".format(avg_cost))

这是我从中获取数据的文件。

def decode(serialized_example):

features = tf.parse_single_example(
serialized_example,
features={'uv': tf.FixedLenFeature([1,20], tf.float32),
'z': tf.FixedLenFeature([1,10], tf.float32)})

return features['uv'], features['z']


def getData():

filename = ["train.tfrecords"]
dataset = tf.data.TFRecordDataset(filename).map(decode)
return dataset

错误:

Traceback (most recent call last):
File "network.py", line 102, in <module>
feed_dict={x: batch_x, y: batch_y})
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 889, in run
run_metadata_ptr)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1089, in _run
np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
File "C:\Users\User\AppData\Roaming\Python\Python36\site-packages\numpy\core\numeric.py", line 531, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

在查看其他问题后,我在想也许我的批处理应该是 ndarray 或其他什么?但我无法弄清楚如何将我的数据集转换成这种形式。我什至无法弄清楚如何在没有迭代器的情况下使用我的数据。任何指导都会很棒!谢谢

最佳答案

请尝试关注,看看是否有帮助。

  1. tf.parse_single_example 不接收批量维度。因此,

    features = tf.parse_single_example(
    serialized_example,
    features={'uv': tf.FixedLenFeature([20], tf.float32),
    'z': tf.FixedLenFeature([10], tf.float32)})
  2. 来自 Simple Batching section of TensorFlow Guide on Dataset API ,您会发现 print(sess.run(next_element)) 运行了 3 次,但 next_element 仅声明了一次。同样,在您的代码中,无需在 for 循环下运行 dataset.make_one_shot_iterator()iterator.get_next()。数据集声明可以放在最开头或 getData() 内部,以便于理解。

  3. 可以使用以下方式形成数据批处理:

    # read file
    dataset = tf.data.TFRecordDataset(filename)
    # parse each instance
    dataset = dataset.map(your_parser_fun, num_parallel_calls=num_threads)
    # preprocessing, e.g. scale to range [0, 1]
    dataset = dataset.map(some_preprocessing_fun)
    # shuffle
    dataset = dataset.shuffle(buffer_size)
    # form batch and epoch
    dataset = dataset.batch(batch_size)
    dataset = dataset.repeat(num_epoch)
    iterator = dataset.make_one_shot_iterator()
    # get a batch
    x_batch, y_batch = self.iterator.get_next()

    # do calculations
    ...
  4. 检查Processing multiple epochs section查看使用 for 循环设置纪元的示例。

关于python - 如何从 TFrecord 创建批处理用于 tensorflow 中的训练网络?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47949159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com