![]() |
![]() |
![]() |
![]() |
總覽
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 的 Iris 資料集。此資料集包含 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
讓我們逐步瞭解以鳶尾花資料集為基礎,使用 ORC 資料集進行 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>