【问题标题】:Can tensorflow handle categorical features with multiple inputs within one column?tensorflow 可以在一列中处理具有多个输入的分类特征吗?
【发布时间】:2017-06-28 15:07:31
【问题描述】:

例如,我有以下 csv 格式的数据:

1、2、1:3:4、2

0、1、3:5、1

...

以逗号分隔的每一列代表一个特征。通常,一个特征是 one-hot(e.g. col0, col1, col3),但在这种情况下,col2 的特征有多个输入(用冒号分隔)。

我确信 tensorflow 可以处理带有 sparse tensor 的 one-hot 特征,但我不确定它是否可以处理像 col2 这样的多个输入的特征?

如果ok的话,在tensorflow的sparse tensor中应该如何表示呢?

【问题讨论】:

    标签: tensorflow sparse-matrix categorical-data


    【解决方案1】:

    TensorFlow 有一些字符串处理操作,可以处理 CSV 中的列表。我首先将列表作为字符串列读取,过程如下:

    def process_list_column(list_column, dtype=tf.float32):
      sparse_strings = tf.string_split(list_column, delimiter=":")
      return tf.SparseTensor(indices=sparse_strings.indices,
                             values=tf.string_to_number(sparse_strings.values,
                                                        out_type=dtype),
                             dense_shape=sparse_strings.dense_shape)
    

    一个使用这个函数的例子:

    # csv_input.csv contains:
    # 1,2,1:3:4,2
    # 0,1,3:5,1
    filename_queue = tf.train.string_input_producer(["csv_input.csv"])
    # Read two lines, batched
    _, lines = tf.TextLineReader().read_up_to(filename_queue, 2)
    columns = tf.decode_csv(lines, record_defaults=[[0], [0], [""], [0]])
    columns[2] = process_list_column(columns[2], dtype=tf.int32)
    
    with tf.Session() as session:
      coordinator = tf.train.Coordinator()
      tf.train.start_queue_runners(session, coord=coordinator)
    
      print(session.run(columns))
    
      coordinator.request_stop()
      coordinator.join()
    

    输出:

    [array([1, 0], dtype=int32), 
     array([2, 1], dtype=int32), 
     SparseTensorValue(indices=array([[0, 0],
           [0, 1],
           [0, 2],
           [1, 0],
           [1, 1]]), 
         values=array([1, 3, 4, 3, 5], dtype=int32), 
         dense_shape=array([2, 3])),
     array([2, 1], dtype=int32)]
    

    【讨论】:

    • 谢谢,这很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2017-06-17
    • 1970-01-01
    • 2019-06-13
    • 2014-09-03
    • 2021-12-17
    • 2018-03-22
    • 2021-01-01
    相关资源
    最近更新 更多