【问题标题】:Pandas input function with multiple value sparse categorical data具有多值稀疏分类数据的 Pandas 输入函数
【发布时间】:2019-02-03 15:47:20
【问题描述】:

给定一个熊猫数据框

df = pd.DataFrame([
    [1, ["a", "b"], 10], 
    [2, ["b"], 20], 
], columns= ["a", "b", "label"])

其中“b”列是一个值列表,代表稀疏的分类数据,我如何创建一个输入函数以提供给训练中的估计器并进行预测?

使用 padas_input_fn 不起作用,因为 b 列:

train_fn = tf.estimator.inputs.pandas_input_fn(x=df[["a", "b"]], y=df.label, shuffle=True)

-- 错误--

 tensorflow.python.framework.errors_impl.InternalError: Unable to get element as bytes.

我可以创建一个tfrecords 文件,使用BytesList 为b 列写入数据,并使用TFRecordDataset 读取它,而不是使用解析函数使用varLenFeature 解析b 列,它可以工作。

但是如何使用内存中的 object/dataframe 和/或 pandas 输入 fn 将这些数据输入估算器?

下面是我的全部代码:

import tensorflow as tf
import pandas as pd

from tensorflow.estimator.inputs import pandas_input_fn
from tensorflow.estimator import DNNRegressor
from tensorflow.feature_column import numeric_column, indicator_column, categorical_column_with_vocabulary_list
from tensorflow.train import Feature, Features, BytesList, FloatList, Example
from tensorflow.python_io import TFRecordWriter

df = pd.DataFrame([
    [1, ["a", "b"], 10], 
    [2, ["b"], 20], 
], columns= ["a", "b", "label"])


writer = TFRecordWriter("test.tfrecord")
for row in df.iterrows():
    dict_feature = {}
    label_values = []
    for e in row[1].iteritems():
        if e[0] =="a":
            dict_feature.update({e[0]: Feature(float_list=FloatList(value=[e[1]]))})
        elif e[0] == "b":
            dict_feature.update({e[0]: Feature(bytes_list=BytesList(value=[m.encode('utf-8') for m in e[1]]))})
        elif e[0] == "label":
            dict_feature.update({e[0]: Feature(float_list=FloatList(value=[e[1]]))})

    example = Example(features=Features(feature=dict_feature))
    writer.write(example.SerializeToString()) 
writer.close()


def parse_tfrecords(example_proto):
    feature_description = {}
    feature_description.update({"a": tf.FixedLenFeature(shape=[], dtype=tf.float32)})
    feature_description.update({"b": tf.VarLenFeature(dtype=tf.string)})
    feature_description.update({"label": tf.FixedLenFeature(shape=[], dtype=tf.float32)})

    parsed_features = tf.parse_single_example(example_proto, feature_description)   
    features = { key: parsed_features[key] for key in ["a", "b"] }
    label = parsed_features["label"]
    return features, label

def tf_record_input_fn(filenames_pattern):

    def _input_fn():
        dataset = tf.data.TFRecordDataset(filenames=filenames_pattern)
        dataset = dataset.shuffle(buffer_size=128)
        dataset = dataset.map(map_func=parse_tfrecords)
        dataset = dataset.batch(batch_size=128)

        return dataset
    return _input_fn


feature_columns = [
    numeric_column("a"),
    indicator_column(categorical_column_with_vocabulary_list("b", vocabulary_list=['a', 'b']))
]
estimator = DNNRegressor(feature_columns=feature_columns, hidden_units=[1])
train_input_fn = tf_record_input_fn("test.tfrecord")
# Next line does not work
# train_input_fn = tf.estimator.inputs.pandas_input_fn(x=df[["a", "b"]], y=df.label, shuffle=True)
estimator.train(train_input_fn)

【问题讨论】:

    标签: pandas tensorflow tensorflow-datasets


    【解决方案1】:

    由于我缺乏使用tensorflow.estimator API 的经验,我没有针对您的查询的完整解决方案,但是您是否可以改用您的数据框?如果b 列列表中的值本质上是分类的,也许您可​​以尝试对它们进行一次性编码,并在此过程中向df 添加更多列?这样一来,您的 df 将对所有估算者变得可处理。

    【讨论】:

      猜你喜欢
      • 2015-06-11
      • 2016-09-26
      • 2019-01-03
      • 1970-01-01
      • 2022-12-17
      • 2020-08-14
      • 1970-01-01
      • 2015-11-15
      • 2017-09-15
      相关资源
      最近更新 更多