在 TensorFlow.org 上查看 | 在 Google Colab 中运行 | 在 GitHub 上查看 | 下载笔记本 |
概览
Apache ORC 是一种流行的列式存储格式。tensorflow-io 软件包提供了读取 Apache ORC 文件的默认实现。
设置
安装所需软件包,并重新启动运行时
pip install tensorflow-io
import tensorflow as tf
import tensorflow_io as tfio
2021-07-30 12:26:35.624072: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcudart.so.11.0
下载 ORC 中的示例数据集文件
您将在此处使用的数据集是 UCI 的 鸢尾花数据集。该数据集包含 3 类,每类 50 个实例,其中每类都指代一种鸢尾花。它具有 4 个属性:(1) 萼片长度,(2) 萼片宽度,(3) 花瓣长度,(4) 花瓣宽度,最后一列包含类标签。
curl -OL https://github.com/tensorflow/io/raw/master/tests/test_orc/iris.orc
ls -l iris.orc
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 144 100 144 0 0 1180 0 --:--:-- --:--:-- --:--:-- 1180 100 3328 100 3328 0 0 13419 0 --:--:-- --:--:-- --:--:-- 0 -rw-rw-r-- 1 kbuilder kokoro 3328 Jul 30 12:26 iris.orc
从该文件中创建一个数据集
dataset = tfio.IODataset.from_orc("iris.orc", capacity=15).batch(1)
2021-07-30 12:26:37.779732: I tensorflow_io/core/kernels/cpu_check.cc:128] Your CPU supports instructions that this TensorFlow IO binary was not compiled to use: AVX2 AVX512F FMA 2021-07-30 12:26:37.887808: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library libcuda.so.1 2021-07-30 12:26:37.979733: E tensorflow/stream_executor/cuda/cuda_driver.cc:328] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected 2021-07-30 12:26:37.979781: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (kokoro-gcp-ubuntu-prod-1874323723): /proc/driver/nvidia/version does not exist 2021-07-30 12:26:37.980766: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2021-07-30 12:26:37.984832: I tensorflow_io/core/kernels/orc/orc_kernels.cc:49] ORC file schema:struct<sepal_length:float,sepal_width:float,petal_length:float,petal_width:float,species:string>
检查数据集
for item in dataset.take(1):
print(item)
(<tf.Tensor: shape=(1,), dtype=float32, numpy=array([5.1], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([3.5], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.4], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=float32, numpy=array([0.2], dtype=float32)>, <tf.Tensor: shape=(1,), dtype=string, numpy=array([b'setosa'], dtype=object)>) 2021-07-30 12:26:38.167628: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:176] None of the MLIR Optimization Passes are enabled (registered 2) 2021-07-30 12:26:38.168103: I tensorflow/core/platform/profile_utils/cpu_utils.cc:114] CPU Frequency: 2000170000 Hz
让我们逐步了解一个基于鸢尾花数据集的 tf.keras 模型训练的端到端示例。
数据预处理
配置哪些列是特征,哪些列是标签
feature_cols = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
label_cols = ["species"]
# select feature columns
feature_dataset = tfio.IODataset.from_orc("iris.orc", columns=feature_cols)
# select label columns
label_dataset = tfio.IODataset.from_orc("iris.orc", columns=label_cols)
2021-07-30 12:26:38.222712: I tensorflow_io/core/kernels/orc/orc_kernels.cc:49] ORC file schema:struct<sepal_length:float,sepal_width:float,petal_length:float,petal_width:float,species:string> 2021-07-30 12:26:38.286470: I tensorflow_io/core/kernels/orc/orc_kernels.cc:49] ORC file schema:struct<sepal_length:float,sepal_width:float,petal_length:float,petal_width:float,species:string>
一个用于将物种映射到浮点数以进行模型训练的实用函数
vocab_init = tf.lookup.KeyValueTensorInitializer(
keys=tf.constant(["virginica", "versicolor", "setosa"]),
values=tf.constant([0, 1, 2], dtype=tf.int64))
vocab_table = tf.lookup.StaticVocabularyTable(
vocab_init,
num_oov_buckets=4)
label_dataset = label_dataset.map(vocab_table.lookup)
dataset = tf.data.Dataset.zip((feature_dataset, label_dataset))
dataset = dataset.batch(1)
def pack_features_vector(features, labels):
"""Pack the features into a single array."""
features = tf.stack(list(features), axis=1)
return features, labels
dataset = dataset.map(pack_features_vector)
构建、编译和训练模型
最后,您可以构建模型并对其进行训练!您将构建一个 3 层 keras 模型,以根据您刚刚处理的数据集预测鸢尾花类的类别。
model = tf.keras.Sequential(
[
tf.keras.layers.Dense(
10, activation=tf.nn.relu, input_shape=(4,)
),
tf.keras.layers.Dense(10, activation=tf.nn.relu),
tf.keras.layers.Dense(3),
]
)
model.compile(optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])
model.fit(dataset, epochs=5)
Epoch 1/5 150/150 [==============================] - 0s 1ms/step - loss: 1.3479 - accuracy: 0.4800 Epoch 2/5 150/150 [==============================] - 0s 920us/step - loss: 0.8355 - accuracy: 0.6000 Epoch 3/5 150/150 [==============================] - 0s 951us/step - loss: 0.6370 - accuracy: 0.7733 Epoch 4/5 150/150 [==============================] - 0s 954us/step - loss: 0.5276 - accuracy: 0.7933 Epoch 5/5 150/150 [==============================] - 0s 940us/step - loss: 0.4766 - accuracy: 0.7933 <tensorflow.python.keras.callbacks.History at 0x7f263b830850>