【问题标题】:How to convert a dict to tensors in tensorflow如何将字典转换为张量流中的张量
【发布时间】:2018-02-13 14:42:49
【问题描述】:

我正在关注关于tensorflow的教程:https://www.tensorflow.org/tutorials/wide

有很多分类特征需要用tf.feature_column.categorical_column_with_vocabulary_list()转换成稀疏矩阵。

但是,我不想使用预定义的 Estimator,

m = tf.estimator.LinearClassifier(
    model_dir=model_dir, feature_columns=base_columns + crossed_columns)

我更喜欢使用装扮好的 NN 模型,其中:

estimator = tf.contrib.learn.Estimator(model_fn=model)
estimator.fit(input_fn=input_fn(df, num_epochs=100, shuffle=True), \ 
              steps=100)

所以在model(),会有

 def model(features, labels, mode): 
    ...
    node = tf.add(tf.matmul(features, w), b)
    ...

然后,我收到如下错误:

 TypeError: Failed to convert object of type <class 'dict'> to Tensor.
 Contents: {'education': <tf.Tensor
 'random_shuffle_queue_DequeueUpTo:1' shape=(?,) dtype=string>, 'age':
 <tf.Tensor 'random_shuffle_queue_DequeueUpTo:2' shape=(?,) dtype=float64> ... 

我的问题是如何将features 转换为可用作输入的张量。

希望我已经清楚地描述了这个问题。提前谢谢你。

【问题讨论】:

    标签: python tensorflow sparse-matrix


    【解决方案1】:

    features 是Tensor 的字典,你可以通过features['education'] 获得Tensor,但是这个Tensor 仍然是string 的类型,它仍然不能使用tf.add(tf.matmul(features, w), b),你应该处理你的字符串类型特征转换为数字特征,如tf.feature_column.categorical_column_with_vocabulary_list()。

    更新:

    你可以查看官方的dnn implementation,在def dnn_logit_fn部分,它使用feature_column_lib.input_layer从features和columns生成输入层,columns是tf.feature_columns.*的列表。

    当定义一个tf.feature_columns.*比如tf.feature_column.categorical_column_with_vocabulary_list()时,它接受必须存在于features.keys()中的字符串作为第一个参数,它连接一个从features到feature_column的张量来告诉tf如何处理原始输入(字符串)张量转换为特征张量(数字)。

    【讨论】:

    • 非常感谢您的回复。但是如何将转换后的features 与tf.contrib.learn.Estimator 联系起来?
    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2020-06-27
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多