gpt4 book ai didi

python - 在 Tensorflow 中创建许多特征列

转载 作者:太空狗 更新时间:2023-10-29 17:33:21 24 4
gpt4 key购买 nike

我正在开始一个 Tensorflow 项目,并且正在定义和创建我的特征列。然而,我有成百上千的特征——这是一个相当广泛的数据集。即使经过预处理和清理,我也有很多列。

创建 feature_column 的传统方法在 Tensorflow tutorial 中定义甚至这个StackOverflow post .您基本上为每个特征列声明并初始化一个 Tensorflow 对象:

gender = tf.feature_column.categorical_column_with_vocabulary_list(
"gender", ["Female", "Male"])

如果您的数据集只有几列,这一切都很好,但就我而言,我肯定不希望有数百行代码来初始化不同的 feature_column 对象。

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

base_columns = [
gender, native_country, education, occupation, workclass, relationship,
age_buckets,
]

最终会传递给您的估算器:

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

那么处理数百列的 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))

这是创建这些特征列的最佳方式吗?还是我缺少 Tensorflow 的某些功能,这些功能让我可以绕过此步骤?

最佳答案

您在问题中发布的内容是有道理的。基于您自己的代码的小型扩展:

import pandas.api.types as ptypes
my_columns = []
for col in df.columns:
if ptypes.is_string_dtype(df[col]):
my_columns.append(tf.feature_column.categorical_column_with_hash_bucket(col,
hash_bucket_size= len(df[col].unique())))

elif ptypes.is_numeric_dtype(df[col]):
my_columns.append(tf.feature_column.numeric_column(col))

elif ptypes.is_categorical_dtype(df[col]):
my_columns.append(tf.feature_column.categorical_column(col,
hash_bucket_size= len(df[col].unique())))

关于python - 在 Tensorflow 中创建许多特征列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com