TableRecordDataset
TableRecordDataset is a PAI-TensorFlow API that reads data from MaxCompute tables row by row and feeds it into a TensorFlow Dataset pipeline. Unlike TableRecordReader, it requires no manual thread or queue management — the Dataset interface handles data prefetching automatically.
GPU-accelerated servers are being phased out. Submit TensorFlow jobs on CPU servers. For GPU-based model training, use Deep Learning Containers (DLC) instead.
How it works
TableRecordDataset works the same way as TensorFlow's native RecordDataset: it provides a data source for Dataset transformations. After creating a TableRecordDataset, chain .batch(), .repeat(), and other Dataset operations to build your input pipeline, then call make_one_shot_iterator().get_next() to pull batches during training.
Access TableRecordDataset through the tf.data namespace:
tf.data.TableRecordDataset(...)Prerequisites
Before you begin, ensure that you have:
PAI-TensorFlow 1.2 or later
A MaxCompute table with the data you want to read
(Optional) Partition names, if reading from partitioned tables
Class definition
class TableRecordDataset(Dataset):
def __init__(self,
filenames,
record_defaults,
selected_cols=None,
excluded_cols=None,
slice_id=0,
slice_count=1,
num_threads=0,
capacity=0):Parameters
| Parameter | Required | Default | Description |
|---|---|---|---|
filenames | Yes | — | List of MaxCompute table names to read. A table can be read more than once. |
record_defaults | Yes | — | Data type for each column to read. If a column is empty, this value is used as the default. If the type is incompatible and cannot be auto-converted, the system raises an exception. Valid values: FLOAT32, FLOAT64, INT32, INT64, BOOL, STRING. |
selected_cols | No | None | Comma-separated list of column names to include. Must be of STRING type. Do not use together with excluded_cols. |
excluded_cols | No | None | Comma-separated list of column names to exclude. Must be of STRING type. Do not use together with selected_cols. |
slice_id | No | 0 | Partition ID for distributed reads. The table is split into slice_count partitions; this parameter identifies which partition the current worker reads. |
slice_count | No | 1 | Total number of partitions in distributed read mode. Set this to the number of workers. |
num_threads | No | 0 | Number of prefetch threads per table in the built-in reader. These threads are independent of compute threads. Valid values: 1–64. When set to 0, the reader uses 1/4 of the available compute threads. For most workloads, the default is sufficient — increase this value only when I/O is the bottleneck. |
capacity | No | 0 | Total number of records to prefetch. When num_threads > 1, each thread prefetches capacity / num_threads records (rounded up). When set to 0, the reader estimates the prefetch size from the average of the first 256 records, targeting approximately 64 MB per thread. For most workloads, the default is sufficient. If you set this manually and a single thread prefetches more than 1 GB, the system logs a warning but continues running. |
If a MaxCompute table column has typeDOUBLE, TensorFlow maps it tonp.float.
Return value
TableRecordDataset returns a new Dataset object. Use it as the input to a pipeline of Dataset transformations.
Each call to get_next() reads the next batch of rows from the table and parses each column into a tensor of the type specified by record_defaults. The output_types of the returned tensors match record_defaults, and output_shapes reflect the number of columns in record_defaults.
Configure table access in the console
Pass table names using the -Dtables flag when submitting a job.
Single table:
pai -name tensorflow1120_cpu_ext -Dtables=odps://algo_platform_dev/tables/sampleMultiple tables (separate with commas):
pai -name tensorflow1120_cpu_ext -Dtables=odps://algo_platform_dev/tables/sample,odps://algo_platform_dev/tables/sample2Partitioned table (append the partition after the table name):
pai -name tensorflow1120_cpu_ext -Dtables=odps://algo_platform_dev/tables/sample/pt=1Example: logistic regression on MaxCompute data
This example walks through a complete training workflow using TableRecordDataset to read tabular data and train a logistic regression model.
Store data column by column in MaxCompute when usingTableRecordDataset. The Dataset interface returns each column as a typed tensor directly, eliminating the string-parsing step required byTableRecordReader.
Step 1: Prepare the data
Create a table.
Create a four-column table in MaxCompute:
odps@ algo_platform_dev> create table sample (col1 double, col2 double, col3 double, col4 double);Expected output:
Data Health Manager: Your health synthesize score is 5, so, your job priority is 7
ID = 201803050245351****6Vgsxo2
OK
odps@ algo_platform_dev> read sample;
+------------+------------+------------+------------+
| col1 | col2 | col3 | col4 |
+------------+------------+------------+------------+
+------------+------------+------------+------------+Import data.
Download test data and upload it using MaxCompute Tunnel. The test data uses commas as delimiters, so pass -fd=, to the upload command:
# View the first three rows of the downloaded file
$ head -n 3 sample.csv
0,0,0.017179100152531324,1
0,1,0.823381420409002,1
0,2,1.6488850495540865,1
# Upload to MaxCompute
odps@ algo_platform_dev> tunnel upload /tmp/data/sample.csv sample -fd=,;Expected output:
Upload session: 20180305135640c8cc650a0000****
Start upload: sample.csv
Using \n to split records
Upload in strict schema mode: true
Total bytes: 260093 Split input to 1 blocks
2018-03-05 13:56:40 scan block: '1'
2018-03-05 13:56:40 scan block complete, blockid=1
2018-03-05 13:56:40 upload block: '1'
2018-03-05 13:56:41 upload block complete, blockid=1
upload complete, average speed is 254 KB/s
OK
odps@ algo_platform_dev> read sample 3;
+------------+------------+------------+------------+
| col1 | col2 | col3 | col4 |
+------------+------------+------------+------------+
| 0.0 | 0.0 | 0.017179100152531324 | 1.0 |
| 0.0 | 1.0 | 0.823381420409002 | 1.0 |
| 0.0 | 2.0 | 1.6488850495540865 | 1.0 |
+------------+------------+------------+------------+Step 2: Define the input and model
Save the following code as lr_dataset.py. The input_fn function creates a TableRecordDataset and reads the table in batches of 128. Unlike TableRecordReader, this approach requires no tf.train.Coordinator or start_queue_runners.
import tensorflow as tf
tf.app.flags.DEFINE_string("tables", "", "tables info")
FLAGS = tf.app.flags.FLAGS
# Define the input pipeline
def input_fn():
# Read all four columns, repeat indefinitely, and batch to 128 rows
dataset = tf.data.TableRecordDataset(
[FLAGS.tables],
record_defaults=[1.0] * 4
).repeat().batch(128)
v1, v2, v3, v4 = dataset.make_one_shot_iterator().get_next()
labels = tf.reshape(tf.cast(v4, tf.int32), [128])
features = tf.stack([v1, v2, v3], axis=1)
return features, labels
# Define the model
def model_fn(features, labels):
W = tf.Variable(tf.zeros([3, 2]))
b = tf.Variable(tf.zeros([2]))
pred = tf.matmul(features, W) + b
loss = tf.reduce_mean(
tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=labels)
)
optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)
return loss, optimizer
features, labels = input_fn()
loss, optimizer = model_fn(features, labels)
init = tf.global_variables_initializer()
local_init = tf.local_variables_initializer()
sess = tf.Session()
sess.run(init)
sess.run(local_init)
for step in range(10000):
_, c = sess.run([optimizer, loss])
if step % 2000 == 0:
print("loss,", c)Step 3: Submit the job
odps@ algo_platform_dev> pai -name tensorflow1120_cpu_ext \
-Dtables=odps://algo_platform_dev/tables/sample \
-Dscript=file:///tmp/lr_dataset.py;Step 4: View the results
Click the LogView link returned after you submit the job to view job logs. The loss output should look similar to:
start launching tensorflow job
('loss,', 0.6931472)
('loss,', 0.007929571)
('loss,', 0.0016527221)
('loss,', 0.0023481336)
('loss,', 0.0011788738)What's next
Submit training jobs in DLC — use GPU-accelerated instances for model training