在Tensorflow中创建许多功能列

Yu *_*hen 13 python neural-network tensorflow

我正在开始使用Tensorflow项目,我正在定义和创建我的功能列.但是,我有数百个功能 - 这是一个非常广泛的数据集.即使在预处理和擦洗之后,我也有很多专栏.

传统的创建方法feature_columnTensorflow教程甚至StackOverflow文章中定义.您基本上为每个功能列声明并初始化Tensorflow对象:

gender = tf.feature_column.categorical_column_with_vocabulary_list(
    "gender", ["Female", "Male"])
Run Code Online (Sandbox Code Playgroud)

如果您的数据集只有几列,这一切都很好,但在我的情况下,我肯定不希望有数百行代码初始化不同的feature_column对象.

解决此问题的最佳方法是什么?我注意到在本教程中,所有列都作为列表收集:

base_columns = [
    gender, native_country, education, occupation, workclass, relationship,
    age_buckets,
]
Run Code Online (Sandbox Code Playgroud)

哪个最终会传递到您的估算工具中:

m = tf.estimator.LinearClassifier(
    model_dir=model_dir, feature_columns=base_columns)
Run Code Online (Sandbox Code Playgroud)

因此,处理feature_column数百列创建的理想方法是将它们直接附加到列表中吗?像这样的东西?

my_columns = []

for col in df.columns:
    if is_string_dtype(df[col]): #is_string_dtype is pandas function
        my_column.append(tf.feature_column.categorical_column_with_hash_bucket(col, 
            hash_bucket_size= len(df[col].unique())))

    elif is_numeric_dtype(df[col]): #is_numeric_dtype is pandas function
        my_column.append(tf.feature_column.numeric_column(col))
Run Code Online (Sandbox Code Playgroud)

这是创建这些功能列的最佳方法吗?或者我错过了Tensorflow的一些功能,让我可以解决这个问题?

gre*_*ess 7

你有什么对我有意义.:)从你自己的代码复制:

my_columns = []

for col in df.columns:
  if is_string_dtype(df[col]): #is_string_dtype is pandas function
    my_columns.append(tf.feature_column.categorical_column_with_hash_bucket(col, 
        hash_bucket_size= len(df[col].unique())))

  elif is_numeric_dtype(df[col]): #is_numeric_dtype is pandas function
    my_columns.append(tf.feature_column.numeric_column(col))
Run Code Online (Sandbox Code Playgroud)