![]() |
![]() |
![]() |
![]() |
This tutorial provides an example of how to load CSV data from a file into a tf.data.Dataset
.
The data used in this tutorial are taken from the Titanic passenger list. The model will predict the likelihood a passenger survived based on characteristics like age, gender, ticket class, and whether the person was traveling alone.
Setup
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
import numpy as np
import tensorflow as tf
TRAIN_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/train.csv"
TEST_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/eval.csv"
train_file_path = tf.keras.utils.get_file("train.csv", TRAIN_DATA_URL)
test_file_path = tf.keras.utils.get_file("eval.csv", TEST_DATA_URL)
Downloading data from https://storage.googleapis.com/tf-datasets/titanic/train.csv 32768/30874 [===============================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tf-datasets/titanic/eval.csv 16384/13049 [=====================================] - 0s 0us/step
# Make numpy values easier to read.
np.set_printoptions(precision=3, suppress=True)
Load data
To start, let's look at the top of the CSV file to see how it is formatted.
!head {train_file_path}
survived,sex,age,n_siblings_spouses,parch,fare,class,deck,embark_town,alone 0,male,22.0,1,0,7.25,Third,unknown,Southampton,n 1,female,38.0,1,0,71.2833,First,C,Cherbourg,n 1,female,26.0,0,0,7.925,Third,unknown,Southampton,y 1,female,35.0,1,0,53.1,First,C,Southampton,n 0,male,28.0,0,0,8.4583,Third,unknown,Queenstown,y 0,male,2.0,3,1,21.075,Third,unknown,Southampton,n 1,female,27.0,0,2,11.1333,Third,unknown,Southampton,n 1,female,14.0,1,0,30.0708,Second,unknown,Cherbourg,n 1,female,4.0,1,1,16.7,Third,G,Southampton,n
You can load this using pandas, and pass the NumPy arrays to TensorFlow. If you need to scale up to a large set of files, or need a loader that integrates with TensorFlow and tf.data then use the tf.data.experimental.make_csv_dataset
function:
The only column you need to identify explicitly is the one with the value that the model is intended to predict.
LABEL_COLUMN = 'survived'
LABELS = [0, 1]
Now read the CSV data from the file and create a dataset.
(For the full documentation, see tf.data.experimental.make_csv_dataset
)
def get_dataset(file_path, **kwargs):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=5, # Artificially small to make examples easier to show.
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True,
**kwargs)
return dataset
raw_train_data = get_dataset(train_file_path)
raw_test_data = get_dataset(test_file_path)
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_core/python/data/experimental/ops/readers.py:521: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version. Instructions for updating: Use `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.experimental.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.experimental_determinstic`.
def show_batch(dataset):
for batch, label in dataset.take(1):
for key, value in batch.items():
print("{:20s}: {}".format(key,value.numpy()))
Each item in the dataset is a batch, represented as a tuple of (many examples, many labels). The data from the examples is organized in column-based tensors (rather than row-based tensors), each with as many elements as the batch size (5 in this case).
It might help to see this yourself.
show_batch(raw_train_data)
sex : [b'female' b'male' b'male' b'male' b'male'] age : [40. 28. 28. 24. 22.] n_siblings_spouses : [0 0 0 0 0] parch : [0 0 0 0 0] fare : [153.462 47.1 8.05 79.2 9.35 ] class : [b'First' b'First' b'Third' b'First' b'Third'] deck : [b'C' b'unknown' b'unknown' b'B' b'unknown'] embark_town : [b'Southampton' b'Southampton' b'Southampton' b'Cherbourg' b'Southampton'] alone : [b'y' b'y' b'y' b'y' b'y']
As you can see, the columns in the CSV are named. The dataset constructor will pick these names up automatically. If the file you are working with does not contain the column names in the first line, pass them in a list of strings to the column_names
argument in the make_csv_dataset
function.
CSV_COLUMNS = ['survived', 'sex', 'age', 'n_siblings_spouses', 'parch', 'fare', 'class', 'deck', 'embark_town', 'alone']
temp_dataset = get_dataset(train_file_path, column_names=CSV_COLUMNS)
show_batch(temp_dataset)
sex : [b'male' b'female' b'male' b'female' b'male'] age : [28. 34. 18. 24. 11.] n_siblings_spouses : [0 0 0 0 0] parch : [0 0 0 0 0] fare : [ 7.75 10.5 73.5 83.158 18.788] class : [b'Third' b'Second' b'Second' b'First' b'Third'] deck : [b'unknown' b'F' b'unknown' b'C' b'unknown'] embark_town : [b'Queenstown' b'Southampton' b'Southampton' b'Cherbourg' b'Cherbourg'] alone : [b'y' b'y' b'y' b'y' b'y']
This example is going to use all the available columns. If you need to omit some columns from the dataset, create a list of just the columns you plan to use, and pass it into the (optional) select_columns
argument of the constructor.
SELECT_COLUMNS = ['survived', 'age', 'n_siblings_spouses', 'class', 'deck', 'alone']
temp_dataset = get_dataset(train_file_path, select_columns=SELECT_COLUMNS)
show_batch(temp_dataset)
age : [27. 28. 31. 45. 66.] n_siblings_spouses : [0 1 0 0 0] class : [b'Third' b'First' b'Second' b'Third' b'Second'] deck : [b'unknown' b'D' b'unknown' b'unknown' b'unknown'] alone : [b'y' b'n' b'y' b'n' b'y']
Data preprocessing
A CSV file can contain a variety of data types. Typically you want to convert from those mixed types to a fixed length vector before feeding the data into your model.
TensorFlow has a built-in system for describing common input conversions: tf.feature_column
, see this tutorial for details.
You can preprocess your data using any tool you like (like nltk or sklearn), and just pass the processed output to TensorFlow.
The primary advantage of doing the preprocessing inside your model is that when you export the model it includes the preprocessing. This way you can pass the raw data directly to your model.
Continuous data
If your data is already in an appropriate numeric format, you can pack the data into a vector before passing it off to the model:
SELECT_COLUMNS = ['survived', 'age', 'n_siblings_spouses', 'parch', 'fare']
DEFAULTS = [0, 0.0, 0.0, 0.0, 0.0]
temp_dataset = get_dataset(train_file_path,
select_columns=SELECT_COLUMNS,
column_defaults = DEFAULTS)
show_batch(temp_dataset)
age : [28. 33. 50. 24. 9.] n_siblings_spouses : [0. 0. 0. 2. 4.] parch : [0. 0. 0. 3. 2.] fare : [ 7.75 9.5 28.712 18.75 31.275]
example_batch, labels_batch = next(iter(temp_dataset))
Here's a simple function that will pack together all the columns:
def pack(features, label):
return tf.stack(list(features.values()), axis=-1), label
Apply this to each element of the dataset:
packed_dataset = temp_dataset.map(pack)
for features, labels in packed_dataset.take(1):
print(features.numpy())
print()
print(labels.numpy())
[[25. 0. 0. 13. ] [27. 1. 0. 13.858] [35. 0. 0. 7.896] [15. 0. 0. 7.225] [31. 0. 0. 10.5 ]] [0 1 0 1 0]
If you have mixed datatypes you may want to separate out these simple-numeric fields. The tf.feature_column
api can handle them, but this incurs some overhead and should be avoided unless really necessary. Switch back to the mixed dataset:
show_batch(raw_train_data)
sex : [b'male' b'male' b'female' b'female' b'male'] age : [28. 29. 28. 47. 28.] n_siblings_spouses : [0 0 0 1 0] parch : [0 0 0 1 0] fare : [13. 30. 7.879 52.554 35.5 ] class : [b'Second' b'First' b'Third' b'First' b'First'] deck : [b'unknown' b'D' b'unknown' b'D' b'C'] embark_town : [b'Southampton' b'Southampton' b'Queenstown' b'Southampton' b'Southampton'] alone : [b'y' b'y' b'y' b'n' b'y']
example_batch, labels_batch = next(iter(temp_dataset))
So define a more general preprocessor that selects a list of numeric features and packs them into a single column:
class PackNumericFeatures(object):
def __init__(self, names):
self.names = names
def __call__(self, features, labels):
numeric_features = [features.pop(name) for name in self.names]
numeric_features = [tf.cast(feat, tf.float32) for feat in numeric_features]
numeric_features = tf.stack(numeric_features, axis=-1)
features['numeric'] = numeric_features
return features, labels
NUMERIC_FEATURES = ['age','n_siblings_spouses','parch', 'fare']
packed_train_data = raw_train_data.map(
PackNumericFeatures(NUMERIC_FEATURES))
packed_test_data = raw_test_data.map(
PackNumericFeatures(NUMERIC_FEATURES))
show_batch(packed_train_data)
sex : [b'male' b'male' b'female' b'male' b'male'] class : [b'Third' b'Third' b'Third' b'Third' b'Third'] deck : [b'unknown' b'unknown' b'unknown' b'unknown' b'unknown'] embark_town : [b'Southampton' b'Southampton' b'Southampton' b'Cherbourg' b'Queenstown'] alone : [b'y' b'y' b'n' b'n' b'n'] numeric : [[59. 0. 0. 7.25 ] [21. 0. 0. 8.05 ] [41. 0. 5. 39.688] [28. 1. 1. 15.246] [ 4. 4. 1. 29.125]]
example_batch, labels_batch = next(iter(packed_train_data))
Data Normalization
Continuous data should always be normalized.
import pandas as pd
desc = pd.read_csv(train_file_path)[NUMERIC_FEATURES].describe()
desc
MEAN = np.array(desc.T['mean'])
STD = np.array(desc.T['std'])
def normalize_numeric_data(data, mean, std):
# Center the data
return (data-mean)/std
Now create a numeric column. The tf.feature_columns.numeric_column
API accepts a normalizer_fn
argument, which will be run on each batch.
Bind the MEAN
and STD
to the normalizer fn using functools.partial
.
# See what you just created.
normalizer = functools.partial(normalize_numeric_data, mean=MEAN, std=STD)
numeric_column = tf.feature_column.numeric_column('numeric', normalizer_fn=normalizer, shape=[len(NUMERIC_FEATURES)])
numeric_columns = [numeric_column]
numeric_column
NumericColumn(key='numeric', shape=(4,), default_value=None, dtype=tf.float32, normalizer_fn=functools.partial(<function normalize_numeric_data at 0x7fd158360268>, mean=array([29.631, 0.545, 0.38 , 34.385]), std=array([12.512, 1.151, 0.793, 54.598])))
When you train the model, include this feature column to select and center this block of numeric data:
example_batch['numeric']
<tf.Tensor: id=550, shape=(5, 4), dtype=float32, numpy= array([[28. , 0. , 0. , 7.05 ], [28. , 0. , 0. , 30.696], [28. , 0. , 0. , 7.729], [42. , 0. , 0. , 7.55 ], [33. , 0. , 0. , 9.5 ]], dtype=float32)>
numeric_layer = tf.keras.layers.DenseFeatures(numeric_columns)
numeric_layer(example_batch).numpy()
array([[-0.13 , -0.474, -0.479, -0.501], [-0.13 , -0.474, -0.479, -0.068], [-0.13 , -0.474, -0.479, -0.488], [ 0.989, -0.474, -0.479, -0.492], [ 0.269, -0.474, -0.479, -0.456]], dtype=float32)
The mean based normalization used here requires knowing the means of each column ahead of time.
Categorical data
Some of the columns in the CSV data are categorical columns. That is, the content should be one of a limited set of options.
Use the tf.feature_column
API to create a collection with a tf.feature_column.indicator_column
for each categorical column.
CATEGORIES = {
'sex': ['male', 'female'],
'class' : ['First', 'Second', 'Third'],
'deck' : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'embark_town' : ['Cherbourg', 'Southhampton', 'Queenstown'],
'alone' : ['y', 'n']
}
categorical_columns = []
for feature, vocab in CATEGORIES.items():
cat_col = tf.feature_column.categorical_column_with_vocabulary_list(
key=feature, vocabulary_list=vocab)
categorical_columns.append(tf.feature_column.indicator_column(cat_col))
# See what you just created.
categorical_columns
[IndicatorColumn(categorical_column=VocabularyListCategoricalColumn(key='sex', vocabulary_list=('male', 'female'), dtype=tf.string, default_value=-1, num_oov_buckets=0)), IndicatorColumn(categorical_column=VocabularyListCategoricalColumn(key='class', vocabulary_list=('First', 'Second', 'Third'), dtype=tf.string, default_value=-1, num_oov_buckets=0)), IndicatorColumn(categorical_column=VocabularyListCategoricalColumn(key='deck', vocabulary_list=('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'), dtype=tf.string, default_value=-1, num_oov_buckets=0)), IndicatorColumn(categorical_column=VocabularyListCategoricalColumn(key='embark_town', vocabulary_list=('Cherbourg', 'Southhampton', 'Queenstown'), dtype=tf.string, default_value=-1, num_oov_buckets=0)), IndicatorColumn(categorical_column=VocabularyListCategoricalColumn(key='alone', vocabulary_list=('y', 'n'), dtype=tf.string, default_value=-1, num_oov_buckets=0))]
categorical_layer = tf.keras.layers.DenseFeatures(categorical_columns)
print(categorical_layer(example_batch).numpy()[0])
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_core/python/feature_column/feature_column_v2.py:4276: IndicatorColumn._variable_shape (from tensorflow.python.feature_column.feature_column_v2) is deprecated and will be removed in a future version. Instructions for updating: The old _FeatureColumn APIs are being deprecated. Please use the new FeatureColumn APIs instead. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_core/python/feature_column/feature_column_v2.py:4331: VocabularyListCategoricalColumn._num_buckets (from tensorflow.python.feature_column.feature_column_v2) is deprecated and will be removed in a future version. Instructions for updating: The old _FeatureColumn APIs are being deprecated. Please use the new FeatureColumn APIs instead. [1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
This will be become part of a data processing input later when you build the model.
Combined preprocessing layer
Add the two feature column collections and pass them to a tf.keras.layers.DenseFeatures
to create an input layer that will extract and preprocess both input types:
preprocessing_layer = tf.keras.layers.DenseFeatures(categorical_columns+numeric_columns)
print(preprocessing_layer(example_batch).numpy()[0])
[ 1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. -0.13 -0.474 -0.479 -0.501 1. 0. ]
Build the model
Build a tf.keras.Sequential
, starting with the preprocessing_layer
.
model = tf.keras.Sequential([
preprocessing_layer,
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
Train, evaluate, and predict
Now the model can be instantiated and trained.
train_data = packed_train_data.shuffle(500)
test_data = packed_test_data
model.fit(train_data, epochs=20)
Epoch 1/20 126/126 [==============================] - 2s 15ms/step - loss: 0.5005 - accuracy: 0.7671 Epoch 2/20 126/126 [==============================] - 1s 4ms/step - loss: 0.4196 - accuracy: 0.8166 Epoch 3/20 126/126 [==============================] - 1s 4ms/step - loss: 0.4039 - accuracy: 0.8325 Epoch 4/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3972 - accuracy: 0.8246 Epoch 5/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3891 - accuracy: 0.8325 Epoch 6/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3721 - accuracy: 0.8405 Epoch 7/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3659 - accuracy: 0.8421 Epoch 8/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3748 - accuracy: 0.8373 Epoch 9/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3599 - accuracy: 0.8517 Epoch 10/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3529 - accuracy: 0.8373 Epoch 11/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3427 - accuracy: 0.8565 Epoch 12/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3384 - accuracy: 0.8596 Epoch 13/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3309 - accuracy: 0.8517 Epoch 14/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3378 - accuracy: 0.8628 Epoch 15/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3273 - accuracy: 0.8596 Epoch 16/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3237 - accuracy: 0.8596 Epoch 17/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3205 - accuracy: 0.8692 Epoch 18/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3215 - accuracy: 0.8565 Epoch 19/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3070 - accuracy: 0.8740 Epoch 20/20 126/126 [==============================] - 1s 4ms/step - loss: 0.3150 - accuracy: 0.8692 <tensorflow.python.keras.callbacks.History at 0x7fd1c82e3828>
Once the model is trained, you can check its accuracy on the test_data
set.
test_loss, test_accuracy = model.evaluate(test_data)
print('\n\nTest Loss {}, Test Accuracy {}'.format(test_loss, test_accuracy))
53/53 [==============================] - 0s 8ms/step - loss: 0.4391 - accuracy: 0.8409 Test Loss 0.43914293209617994, Test Accuracy 0.8409090638160706
Use tf.keras.Model.predict
to infer labels on a batch or a dataset of batches.
predictions = model.predict(test_data)
# Show some results
for prediction, survived in zip(predictions[:10], list(test_data)[0][1][:10]):
print("Predicted survival: {:.2%}".format(prediction[0]),
" | Actual outcome: ",
("SURVIVED" if bool(survived) else "DIED"))
Predicted survival: 8.15% | Actual outcome: DIED Predicted survival: 10.84% | Actual outcome: SURVIVED Predicted survival: 8.76% | Actual outcome: DIED Predicted survival: 18.50% | Actual outcome: DIED Predicted survival: 77.37% | Actual outcome: DIED