【问题标题】:What is the best way to get string column from a Pandas Dataframe into a TensorFLow model?将字符串列从 Pandas Dataframe 获取到 TensorFLow 模型的最佳方法是什么?
【发布时间】:2018-10-02 10:50:06
【问题描述】:

假设我有一些包含一些字符串列的 Pandas DataFrame:

Animal  Name    Age  ...
Cat     Fluffy  2    ...
Dog     Denton  3    ...

我想将 Animal 列(具有一组已知值)输入到我的训练模型中(用于线性回归)。我查看了以下选项:

  1. tf.feature_column.categorical_column_with_vocabulary_list 但看起来你将它与 tf.feature_column.make_parse_example_spec 和协议缓冲区一起使用。
  2. tf.one_hot 听起来可能会有所帮助,但示例代码确实没有帮助我理解。

或者我应该自己编写一些东西来将字符串转换为数字/布尔数据?

【问题讨论】:

    标签: python pandas tensorflow categorical-data one-hot-encoding


    【解决方案1】:

    tf.feature_column 命名空间可以忽略如下:

    使用 pandas 将您的字符串列自动编码为数值。原始数据框中的类别列将具有 cat.codes 属性。您可以创建一个新的 pandas 列并将这些 cat.codes 复制到其中。新列将是一个数字列,其中填充了神经网络所需的数字。

    使用这样的代码查找类别列,并创建新列:

    str_cols = [cn for cn in d.columns if is_string_dtype(d[cn])]
    add_code_columns = [cn for cn in d.columns if (cn in cat_cols) and (cn in str_cols)]
    
    for cn in add_code_columns:
      codecolname = cn + "_code"
      if not codecolname in d.columns:
        d[codecolname] = d[cn].cat.codes
    

    【讨论】:

      【解决方案2】:

      您可以使用tf.feature_column.input_layer 函数来创建输入张量。首先,必须将分类列包装为指示符或嵌入列。

      例子:

      # Create columns
      vocab_list = ['a','b','c','d']
      letter_column = tf.feature_column.categorical_column_with_vocabulary_list(
          key="letter",
          vocabulary_list=vocab_list)
      embedded_column = tf.feature_column.embedding_column(letter_column, 8)
      indicator_column = tf.feature_column.indicator_column(letter_column)
      
      # Create features and use input_layer to get a tensor
      features = {'letter': ['c']}
      inp = tf.feature_column.input_layer(features,[embedded_column, indicator_column])
      
      # Print value of inp
      with tf.Session() as s:
        s.run([tf.global_variables_initializer(),
               tf.local_variables_initializer(),
               tf.tables_initializer()])
        print(s.run(inp))
      

      输出(前 8 个数字可能不同):

      [[ 0.29994071 -0.07036652 -0.23166095  0.0681599  -0.07477489 -0.25384274
        -0.31568974 -0.09161812  0.          0.          1.          0.        ]]
      

      inp 是一个有 12 个元素的张量。前 8 个是从 embedded_column(可训练)计算的嵌入,后 4 个是来自 indicator_column 的值的多热表示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-31
        • 2015-07-02
        相关资源
        最近更新 更多