Vincent Teyssier
Vincent Teyssier

Reputation: 2217

How to declare categorical columns in decode_csv when using Tensorflow dataset?

I am trying to read columns from a csv file using the Tensorflow Dataset API.

I first list the names of my columns and how many I have:

numerical_feature_names = ["N1", "N2"]
categorical_feature_names = ["C3", "C4", "C5"]
amount_of_columns_csv = 5

I then declare my column type:

feature_columns = [tf.feature_column.numeric_column(k) for k in numerical_feature_names]

for k in categorical_feature_names:
    current_categorical_column = tf.feature_column.categorical_column_with_hash_bucket(
         key=k, 
         hash_bucket_size=40)

feature_columns.append(tf.feature_column.indicator_column(current_categorical_column))

And finally my input function:

def my_input_fn(file_path, perform_shuffle=False, repeat_count=1):
   def  decode_csv(line):
       parsed_line = tf.decode_csv(line, [[0.]]*amount_of_columns_csv, field_delim=';', na_value='-1')
       d = dict(zip(feature_names, parsed_line)), label
       return d

   dataset = (tf.data.TextLineDataset(file_path) # Read text file
       .skip(1) # Skip header row
       .map(decode_csv)) # Transform each elem by applying decode_csv fn
   if perform_shuffle:
       # Randomizes input using a window of 512 elements (read into memory)
       dataset = dataset.shuffle(buffer_size=BATCH_SIZE)
   dataset = dataset.repeat(repeat_count) # Repeats dataset this # times
   dataset = dataset.batch(BATCH_SIZE)  # Batch size to use
   iterator = dataset.make_one_shot_iterator()
   batch_features, batch_labels = iterator.get_next()
   return batch_features, batch_labels

How should I declare my record_defaults argument in the decode_csv call? For the moment I only capture numerical columns with [[0.]]

If I had thousand of columns with mixed numerical and categorical columns, how could I avoid having to manually declare the structure in the decode_csv function ?

Upvotes: 3

Views: 701

Answers (2)

eilalan
eilalan

Reputation: 689

tf.data.experimental.make_csv_dataset will do the work for you. Will take you from CSV to tf.feature_columns

Upvotes: 1

Vincent Teyssier
Vincent Teyssier

Reputation: 2217

Instead of trying to load the csv in Tensorflow directly, I first load it into a panda dataframe, iterate over the columns dtype and set my type array so I can reuse it in Tensorflow input function, code below:

CSV_COLUMN_NAMES = pd.read_csv(FILE_TRAIN, nrows=1).columns.tolist()
train = pd.read_csv(FILE_TRAIN, names=CSV_COLUMN_NAMES, header=0)
train_x, train_y = train, train.pop('labels')

test = pd.read_csv(FILE_TEST, names=CSV_COLUMN_NAMES, header=0)
test_x, test_y = test, test.pop('labels')

# iterate over the columns type to create my column array
for column in train.columns:
    print (train[column].dtype)
    if(train[column].dtype == np.float64 or train[column].dtype == np.int64):
        numerical_feature_names.append(column)
    else:
        categorical_feature_names.append(column)

feature_columns = [tf.feature_column.numeric_column(k) for k in numerical_feature_names]

# here an example of how you could process categorical columns
for k in categorical_feature_names:
    current_bucket = train[k].nunique()
    if current_bucket>10:
        feature_columns.append(
            tf.feature_column.indicator_column(
                tf.feature_column.categorical_column_with_vocabulary_list(key=k, vocabulary_list=train[k].unique())
            )
        )
    else:
        feature_columns.append(
            tf.feature_column.indicator_column(
                tf.feature_column.categorical_column_with_hash_bucket(key=k, hash_bucket_size=current_bucket)
            )
        )

And finally the input function

# input_fn for training, convertion of dataframe to dataset
def train_input_fn(features, labels, batch_size, repeat_count):
    dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
    dataset = dataset.shuffle(256).repeat(repeat_count).batch(batch_size)
    return dataset

Upvotes: 2

Related Questions