Cast String to Float Is Not Supported in Linear Model

Tensorflow: Cast string to float is not supported error when using tflearn despite having no strings in data

I had the same problem, you write:

learning_rate = '0.001'

But the learning_rate is a float not a string so just write:

learning_rate = 0.001

Tensorflow Error UnimplementedError: Cast string to float is not supported - Linear Classifier Model using Estimator

While debugging this issue, the issue was resolved but I am not sure what step did actually resolve it.

I have tried below things while debugging this issue:

  1. In reference to the stackoverflow thread: float64 with pandas to_csv, changed the floating type format which is written to CSV file as below:

Prior Code:

train.to_csv('train.csv', header=False, index=False)
valid.to_csv('valid.csv', header=False, index=False)

Modified Code:

train.to_csv('train.csv', header=False, index=False, float_format='%.4f')
valid.to_csv('valid.csv', header=False, index=False, float_format='%.4f')

  1. Added columns one by one to the input CSV file and checked the
    corresponding default datatypes. I found one of the columns in which
    the pandas written CSV file had 0.0 (although it was being read as integer value). In Tensorflow it was being
    read as int64. Changing the datatype to float64 resolved the mismatching datatype issue.

Now the model is up and running.

UnimplementedError: Cast string to float is not supported while using Tensorflow

I can reproduce your error by using a tf.feature_column.numeric_column on a dataframe column that has string values.

import tensorflow as tf
import pandas as pd
import numpy as np

df = pd.DataFrame({
'float_values': np.random.rand(15),
'string_values': np.random.randint(0, 10, (15,))
})

df['string_values'] = df['string_values'].astype(str)
float_values     float64
string_values object
ds = tf.data.Dataset.from_tensors(dict(df))

float_column = tf.feature_column.numeric_column('float_values')
string_column = tf.feature_column.numeric_column('string_values')

# This works, the 'float_values' column is numeric
float_layer = tf.keras.layers.DenseFeatures(float_column)
float_layer(next(iter(ds)))

# This doesn't work, the 'string_values' column is string
string_layer = tf.keras.layers.DenseFeatures(string_column)
string_layer(next(iter(ds)))

tensorflow.python.framework.errors_impl.UnimplementedError: Cast string to float is not supported [Op:Cast]

Make sure all your dataframe is of dtype float/int.

for col in NUMERIC_COLUMNS:
df[col] = pd.to_numeric(df[col])

Note that there might be a better to cast to numeric, I am admittedly not a Pandas expert.



Related Topics



Leave a reply



Submit