【问题标题】:Train Tensorflow model with estimator (from_generator)使用估计器(from_generator)训练 TensorFlow 模型
【发布时间】:2018-09-15 08:22:58
【问题描述】:

我正在尝试使用生成器训练估计器,但我想为每次迭代向该估计器提供一组样本。我显示代码:

def _generator():
for i in range(100):
    feats  = np.random.rand(4,2)
    labels = np.random.rand(4,1)

    yield feats, labels


def input_func_gen():
    shapes = ((4,2),(4,1))
    dataset = tf.data.Dataset.from_generator(generator=_generator,
                                         output_types=(tf.float32, tf.float32),
                                         output_shapes=shapes)
dataset = dataset.batch(4)
# dataset = dataset.repeat(20)
iterator = dataset.make_one_shot_iterator()
features_tensors, labels = iterator.get_next()
features = {'x': features_tensors}
return features, labels


x_col = tf.feature_column.numeric_column(key='x', shape=(4,2))
es = tf.estimator.LinearRegressor(feature_columns=[x_col],model_dir=tf_data)
es = es.train(input_fn=input_func_gen,steps = None)

当我运行这段代码时,它会引发这个错误:

    raise ValueError(err.message)
ValueError: Dimensions must be equal, but are 2 and 3 for 'linear/head/labels/assert_equal/Equal' (op: 'Equal') with input shapes: [2], [3].

我该如何调用这个结构??

谢谢!!!

【问题讨论】:

    标签: python tensorflow tensorflow-datasets tensorflow-estimator


    【解决方案1】:

    批量大小由 Tensorflow 自动计算并添加到张量形状中,因此不必手动完成。您的生成器还应定义为输出单个样本。

    假设您的形状位置 0 中的 4 用于批量大小,那么:

    import tensorflow as tf
    import numpy
    
    def _generator():
        for i in range(100):
            feats  = numpy.random.rand(2)
            labels = numpy.random.rand(1)
    
            yield feats, labels
    
    
    def input_func_gen():
        shapes = ((2),(1))
        dataset = tf.data.Dataset.from_generator(generator=_generator,
                                             output_types=(tf.float32, tf.float32),
                                             output_shapes=shapes)
        dataset = dataset.batch(4)
        # dataset = dataset.repeat(20)
        iterator = dataset.make_one_shot_iterator()
        features_tensors, labels = iterator.get_next()
        features = {'x': features_tensors}
        return features, labels
    
    
    x_col = tf.feature_column.numeric_column(key='x', shape=(2))
    es = tf.estimator.LinearRegressor(feature_columns=[x_col])
    es = es.train(input_fn=input_func_gen,steps = None)
    

    【讨论】:

    • 谢谢你救了我的命,你说Your generator should also be defined to output single samples,每个输出只有一个样本,这是数据生成器的规则,还是可能产生多个样本?任何示例代码?非常感谢
    • 我的意思是你的生成器不应该输出批处理数据(无论数据是什么)。 Tensorflow 将自己进行批处理,根据需要多次调用生成器。
    • 感谢您的回复。如果 tf.data.TextLineDataset(data_file), 我发现这比 from_generator 快,因为正如你所说,它每次只产生一个项目。那么有什么让它更快的想法吗?
    猜你喜欢
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多