【发布时间】:2017-08-30 15:56:12
【问题描述】:
我在很长一段时间(几个小时)内搜索了我的问题的正确答案,但没有结果,所以我来了。我想我遗漏了一些明显的东西,但我不知道是什么......
问题:使用队列读取 CSV 文件并使用 input_fn 训练 Estimator,而无需每次都重新加载 Graph(这非常慢)。
我创建了一个自定义模型,它为我提供了一个 model_fn 函数来创建我自己的估算器:
tf.estimator.Estimator(model_fn=model_fn, params=model_params)
之后,我需要读取一个非常大的 CSV 文件(无法加载到内存中),所以我决定使用 Queue(似乎是最好的解决方案):
nb_features = 10
queue = tf.train.string_input_producer(["test.csv"],
shuffle=False)
reader = tf.TextLineReader()
key, value = reader.read(queue)
record_defaults = [[0] for _ in range(nb_features+1)]
cols = tf.decode_csv(value, record_defaults=record_defaults)
features = tf.stack(cols[0:len(cols)-1]) # Take all columns without the last
label = tf.stack(cols[len(cols)-1]) # Take last column
我觉得这段代码没问题。
然后,主要代码:
with tf.Session() as sess:
tf.logging.set_verbosity(tf.logging.INFO)
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
# Return a Tensor of 1000 features/labels
def get_inputs():
print("input call !")
xs = []
ys = []
for i in range(1000):
x, y = sess.run([features, label])
xs.append(x)
ys.append(y)
return tf.constant(np.asarray(xs), dtype=tf.float32), tf.constant(np.asarray(ys))
estimator.train(input_fn=get_inputs,
steps=100)
coord.request_stop()
coord.join(threads)
如你所见,这里有很多丑陋的东西......
我想要什么:我希望 train 函数在每个步骤中使用一批新的特征。但是在这里,它在 100 个步骤中使用了相同批次的 1000 个特征,因为 get_inputs 函数只是在我们开始训练时调用。有没有简单的方法来做到这一点?
我尝试使用 step=1 循环 estimator.train,但这每次都会重新加载图表并且变得非常慢。
我现在不知道该怎么做,也不知道有没有可能..
谢谢你帮助我!
【问题讨论】:
标签: python-3.x csv machine-learning tensorflow