数据流水线技术

This commit is contained in:
estomm
2021-04-24 10:28:11 +08:00
parent 71a4306ee3
commit 9b1a924eb6
32 changed files with 1432 additions and 22 deletions

View File

@@ -0,0 +1,125 @@
{
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python388jvsc74a57bd05ef0042cb263260037aa2928643ae94e240dd3afaec7872ebebe4f07619ddd0c",
"display_name": "Python 3.8.8 64-bit ('ml': conda)"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Downloading data from https://storage.googleapis.com/tff-datasets-public/fed_emnist_digitsonly.tar.bz2\n",
"97402880/97398400 [==============================] - 6s 0us/step\n",
"WARNING:tensorflow:AutoGraph could not transform <function client_data.<locals>.<lambda> at 0x0000016F610DF820> and will run it as-is.\n",
"Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n",
"Cause: module 'gast' has no attribute 'Index'\n",
"To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n",
"WARNING: AutoGraph could not transform <function client_data.<locals>.<lambda> at 0x0000016F610DF820> and will run it as-is.\n",
"Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n",
"Cause: module 'gast' has no attribute 'Index'\n",
"To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n",
"WARNING:tensorflow:AutoGraph could not transform <function client_data.<locals>.<lambda> at 0x0000016F610DD940> and will run it as-is.\n",
"Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n",
"Cause: module 'gast' has no attribute 'Index'\n",
"To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n",
"WARNING: AutoGraph could not transform <function client_data.<locals>.<lambda> at 0x0000016F610DD940> and will run it as-is.\n",
"Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n",
"Cause: module 'gast' has no attribute 'Index'\n",
"To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n",
"WARNING:tensorflow:AutoGraph could not transform <function client_data.<locals>.<lambda> at 0x0000016F6231CB80> and will run it as-is.\n",
"Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n",
"Cause: module 'gast' has no attribute 'Index'\n",
"To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n",
"WARNING: AutoGraph could not transform <function client_data.<locals>.<lambda> at 0x0000016F6231CB80> and will run it as-is.\n",
"Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.\n",
"Cause: module 'gast' has no attribute 'Index'\n",
"To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert\n"
]
},
{
"output_type": "error",
"ename": "TypeError",
"evalue": "from_keras_model() got an unexpected keyword argument 'dummy_batch'",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-2-48f9e54d058c>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m 29\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 30\u001b[0m \u001b[1;31m# Simulate a few rounds of training with the selected client devices.\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 31\u001b[1;33m trainer = tff.learning.build_federated_averaging_process(\n\u001b[0m\u001b[0;32m 32\u001b[0m \u001b[0mmodel_fn\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 33\u001b[0m client_optimizer_fn=lambda: tf.keras.optimizers.SGD(0.1))\n",
"\u001b[1;32mD:\\anaconda\\envs\\ml\\lib\\site-packages\\tensorflow_federated\\python\\learning\\federated_averaging.py\u001b[0m in \u001b[0;36mbuild_federated_averaging_process\u001b[1;34m(model_fn, client_optimizer_fn, server_optimizer_fn, client_weight_fn, broadcast_process, aggregation_process, model_update_aggregation_factory, use_experimental_simulation_loop)\u001b[0m\n\u001b[0;32m 221\u001b[0m use_experimental_simulation_loop)\n\u001b[0;32m 222\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 223\u001b[1;33m return optimizer_utils.build_model_delta_optimizer_process(\n\u001b[0m\u001b[0;32m 224\u001b[0m \u001b[0mmodel_fn\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 225\u001b[0m \u001b[0mmodel_to_client_delta_fn\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mclient_fed_avg\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32mD:\\anaconda\\envs\\ml\\lib\\site-packages\\tensorflow_federated\\python\\learning\\framework\\optimizer_utils.py\u001b[0m in \u001b[0;36mbuild_model_delta_optimizer_process\u001b[1;34m(model_fn, model_to_client_delta_fn, server_optimizer_fn, broadcast_process, aggregation_process, model_update_aggregation_factory)\u001b[0m\n\u001b[0;32m 608\u001b[0m \u001b[0mpy_typecheck\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcheck_callable\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mserver_optimizer_fn\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 609\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 610\u001b[1;33m \u001b[0mmodel_weights_type\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mmodel_utils\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mweights_type_from_model\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmodel_fn\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 611\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 612\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mbroadcast_process\u001b[0m \u001b[1;32mis\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32mD:\\anaconda\\envs\\ml\\lib\\site-packages\\tensorflow_federated\\python\\learning\\model_utils.py\u001b[0m in \u001b[0;36mweights_type_from_model\u001b[1;34m(model)\u001b[0m\n\u001b[0;32m 98\u001b[0m \u001b[1;31m# with variables created for this model.\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 99\u001b[0m \u001b[1;32mwith\u001b[0m \u001b[0mtf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mGraph\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mas_default\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 100\u001b[1;33m \u001b[0mmodel\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 101\u001b[0m \u001b[0mpy_typecheck\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcheck_type\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmodel\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mmodel_lib\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mModel\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 102\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mtype_conversions\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtype_from_tensors\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mModelWeights\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfrom_model\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmodel\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;32m<ipython-input-2-48f9e54d058c>\u001b[0m in \u001b[0;36mmodel_fn\u001b[1;34m()\u001b[0m\n\u001b[0;32m 22\u001b[0m kernel_initializer='zeros')\n\u001b[0;32m 23\u001b[0m ])\n\u001b[1;32m---> 24\u001b[1;33m return tff.learning.from_keras_model(\n\u001b[0m\u001b[0;32m 25\u001b[0m \u001b[0mmodel\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 26\u001b[0m \u001b[0mdummy_batch\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0msample_batch\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: from_keras_model() got an unexpected keyword argument 'dummy_batch'"
]
}
],
"source": [
"import tensorflow as tf\n",
"import tensorflow_federated as tff\n",
"\n",
"# Load simulation data.\n",
"source, _ = tff.simulation.datasets.emnist.load_data()\n",
"def client_data(n):\n",
" return source.create_tf_dataset_for_client(source.client_ids[n]).map(\n",
" lambda e: (tf.reshape(e['pixels'], [-1]), e['label'])\n",
" ).repeat(10).batch(20)\n",
"\n",
"# Pick a subset of client devices to participate in training.\n",
"train_data = [client_data(n) for n in range(3)]\n",
"\n",
"# Grab a single batch of data so that TFF knows what data looks like.\n",
"sample_batch = tf.nest.map_structure(\n",
" lambda x: x.numpy(), iter(train_data[0]).next())\n",
"\n",
"# Wrap a Keras model for use with TFF.\n",
"def model_fn():\n",
" model = tf.keras.models.Sequential([\n",
" tf.keras.layers.Dense(10, tf.nn.softmax, input_shape=(784,),\n",
" kernel_initializer='zeros')\n",
" ])\n",
" return tff.learning.from_keras_model(\n",
" model,\n",
" dummy_batch=sample_batch,\n",
" loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n",
" metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\n",
"\n",
"# Simulate a few rounds of training with the selected client devices.\n",
"trainer = tff.learning.build_federated_averaging_process(\n",
" model_fn,\n",
" client_optimizer_fn=lambda: tf.keras.optimizers.SGD(0.1))\n",
"state = trainer.initialize()\n",
"for _ in range(5):\n",
" state, metrics = trainer.next(state, train_data)\n",
" print (metrics.loss)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,90 @@
{
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python388jvsc74a57bd05ef0042cb263260037aa2928643ae94e240dd3afaec7872ebebe4f07619ddd0c",
"display_name": "Python 3.8.8 64-bit ('ml': conda)"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"source": [
"# 使用 Python generator 加载数据"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def count(stop):\n",
" i = 0\n",
" while i<stop:\n",
" yield i,i+1,i+2\n",
" i += 1"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"ds_counter = tf.data.Dataset.from_generator(count, args=[25], output_types=tf.int32, output_shapes = (3,),)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[[ 0 1 2]\n [ 1 2 3]\n [ 2 3 4]\n [ 3 4 5]\n [ 4 5 6]\n [ 5 6 7]\n [ 6 7 8]\n [ 7 8 9]\n [ 8 9 10]\n [ 9 10 11]]\n[[10 11 12]\n [11 12 13]\n [12 13 14]\n [13 14 15]\n [14 15 16]\n [15 16 17]\n [16 17 18]\n [17 18 19]\n [18 19 20]\n [19 20 21]]\n[[20 21 22]\n [21 22 23]\n [22 23 24]\n [23 24 25]\n [24 25 26]\n [ 0 1 2]\n [ 1 2 3]\n [ 2 3 4]\n [ 3 4 5]\n [ 4 5 6]]\n[[ 5 6 7]\n [ 6 7 8]\n [ 7 8 9]\n [ 8 9 10]\n [ 9 10 11]\n [10 11 12]\n [11 12 13]\n [12 13 14]\n [13 14 15]\n [14 15 16]]\n[[15 16 17]\n [16 17 18]\n [17 18 19]\n [18 19 20]\n [19 20 21]\n [20 21 22]\n [21 22 23]\n [22 23 24]\n [23 24 25]\n [24 25 26]]\n[[ 0 1 2]\n [ 1 2 3]\n [ 2 3 4]\n [ 3 4 5]\n [ 4 5 6]\n [ 5 6 7]\n [ 6 7 8]\n [ 7 8 9]\n [ 8 9 10]\n [ 9 10 11]]\n[[10 11 12]\n [11 12 13]\n [12 13 14]\n [13 14 15]\n [14 15 16]\n [15 16 17]\n [16 17 18]\n [17 18 19]\n [18 19 20]\n [19 20 21]]\n[[20 21 22]\n [21 22 23]\n [22 23 24]\n [23 24 25]\n [24 25 26]\n [ 0 1 2]\n [ 1 2 3]\n [ 2 3 4]\n [ 3 4 5]\n [ 4 5 6]]\n[[ 5 6 7]\n [ 6 7 8]\n [ 7 8 9]\n [ 8 9 10]\n [ 9 10 11]\n [10 11 12]\n [11 12 13]\n [12 13 14]\n [13 14 15]\n [14 15 16]]\n[[15 16 17]\n [16 17 18]\n [17 18 19]\n [18 19 20]\n [19 20 21]\n [20 21 22]\n [21 22 23]\n [22 23 24]\n [23 24 25]\n [24 25 26]]\n"
]
}
],
"source": [
"for count_batch in ds_counter.repeat().batch(10).take(10):\n",
" print(count_batch.numpy())"
]
},
{
"source": [
"## 使用Python生成器解决多个文件加载的问题。\n",
"\n",
"考虑是否要用这种方式,加载Python生成器中的多个数据。"
],
"cell_type": "markdown",
"metadata": {}
}
]
}

View File

@@ -0,0 +1,228 @@
{
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python388jvsc74a57bd05ef0042cb263260037aa2928643ae94e240dd3afaec7872ebebe4f07619ddd0c",
"display_name": "Python 3.8.8 64-bit ('ml': conda)"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"source": [
"# 1 tf record 实例"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/fsns-20160927/testdata/fsns-00000-of-00001\n",
"7905280/7904079 [==============================] - 103s 13us/step\n"
]
}
],
"source": [
"fsns_test_file = tf.keras.utils.get_file(\"fsns.tfrec\", \"https://storage.googleapis.com/download.tensorflow.org/data/fsns-20160927/testdata/fsns-00000-of-00001\")\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<TFRecordDatasetV2 shapes: (), types: tf.string>"
]
},
"metadata": {},
"execution_count": 3
}
],
"source": [
"# 使用TFRecordDataset加载二进制的数据\n",
"dataset = tf.data.TFRecordDataset(filenames = [fsns_test_file])\n",
"dataset"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"bytes_list {\n",
" value: \"Rue Perreyon\"\n",
"}"
]
},
"metadata": {},
"execution_count": 4
}
],
"source": [
"raw_example = next(iter(dataset))\n",
"parsed = tf.train.Example.FromString(raw_example.numpy())\n",
"\n",
"parsed.features.feature['image/text']"
]
},
{
"source": [
"# 2 写入tf example消息格式\n",
"第二种加载大数据的方法\n",
"\n",
"将原来的数据处理成tfrecord格式进行加载。\n",
"\n",
"## 数据类型\n",
"### tf.train.BytesList(可强制转换自以下类型)\n",
"* string\n",
"* byte\n",
"### tf.train.FloatList(可强制转换自以下类型)\n",
"* float (float32)\n",
"* double (float64)\n",
"### tf.train.Int64List(可强制转换自以下类型)\n",
"* bool\n",
"* enum\n",
"* int32\n",
"* uint32\n",
"* int64\n",
"* uint64"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"\n",
"import numpy as np\n",
"import IPython.display as display"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# The following functions can be used to convert a value to a type compatible\n",
"# with tf.Example.\n",
"# 定义一系列格式转换函数\n",
"\n",
"def _bytes_feature(value):\n",
" \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n",
" if isinstance(value, type(tf.constant(0))):\n",
" value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n",
" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n",
"\n",
"def _float_feature(value):\n",
" \"\"\"Returns a float_list from a float / double.\"\"\"\n",
" return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n",
"\n",
"def _int64_feature(value):\n",
" \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n",
" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"bytes_list {\n value: \"test_string\"\n}\n\nbytes_list {\n value: \"test_bytes\"\n}\n\nfloat_list {\n value: 2.7182817\n}\n\nint64_list {\n value: 1\n}\n\nint64_list {\n value: 1\n}\n\n"
]
}
],
"source": [
"print(_bytes_feature(b'test_string'))\n",
"print(_bytes_feature(u'test_bytes'.encode('utf-8')))\n",
"\n",
"print(_float_feature(np.exp(1)))\n",
"\n",
"print(_int64_feature(True))\n",
"print(_int64_feature(1))"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"b'\\x12\\x06\\n\\x04T\\xf8-@'"
]
},
"metadata": {},
"execution_count": 9
}
],
"source": [
"# serializetostring()格式化为二进制字符串\n",
"feature = _float_feature(np.exp(1))\n",
"\n",
"feature.SerializeToString()"
]
},
{
"source": [
"# 3 读取tf example 消息格式"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}

View File

@@ -0,0 +1,171 @@
{
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python388jvsc74a57bd05ef0042cb263260037aa2928643ae94e240dd3afaec7872ebebe4f07619ddd0c",
"display_name": "Python 3.8.8 64-bit ('ml': conda)"
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"source": [
"# 1使用tf.TextLineReader"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"directory_url = 'https://storage.googleapis.com/download.tensorflow.org/data/illiad/'\n",
"file_names = ['cowper.txt', 'derby.txt', 'butler.txt']\n",
"\n",
"file_paths = [\n",
" tf.keras.utils.get_file(file_name, directory_url + file_name)\n",
" for file_name in file_names\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"b\"\\xef\\xbb\\xbfAchilles sing, O Goddess! Peleus' son;\"\nb'His wrath pernicious, who ten thousand woes'\nb\"Caused to Achaia's host, sent many a soul\"\nb'Illustrious into Ades premature,'\nb'And Heroes gave (so stood the will of Jove)'\n"
]
}
],
"source": [
"# 使用textlinedataset一次读取某个文件中的一行\n",
"dataset = tf.data.TextLineDataset(file_paths)\n",
"for line in dataset.take(5):\n",
" print(line.numpy())"
]
},
{
"source": [
"# 2 使用interleave进行读取?"
],
"cell_type": "markdown",
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\nb\"\\xef\\xbb\\xbfAchilles sing, O Goddess! Peleus' son;\"\nb\"\\xef\\xbb\\xbfOf Peleus' son, Achilles, sing, O Muse,\"\nb'\\xef\\xbb\\xbfSing, O goddess, the anger of Achilles son of Peleus, that brought'\n\nb'His wrath pernicious, who ten thousand woes'\nb'The vengeance, deep and deadly; whence to Greece'\nb'countless ills upon the Achaeans. Many a brave soul did it send'\n\nb\"Caused to Achaia's host, sent many a soul\"\nb'Unnumbered ills arose; which many a soul'\nb'hurrying down to Hades, and many a hero did it yield a prey to dogs and'\n"
]
}
],
"source": [
"# 要在文件之间替换,请使用Dataset.interleave。这样可以更轻松地将文件混在一起。这是每种翻译的第一,第二和第三行:\n",
"# 这种方法可以一次读取多个文件的数据,并混合起来诶!!!666\n",
"files_ds = tf.data.Dataset.from_tensor_slices(file_paths)\n",
"lines_ds = files_ds.interleave(tf.data.TextLineDataset, cycle_length=3)\n",
"\n",
"for i, line in enumerate(lines_ds.take(9)):\n",
" if i % 3 == 0:\n",
" print()\n",
" print(line.numpy())"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Downloading data from https://storage.googleapis.com/tf-datasets/titanic/train.csv\n",
"32768/30874 [===============================] - 0s 10us/step\n",
"b'survived,sex,age,n_siblings_spouses,parch,fare,class,deck,embark_town,alone'\n",
"b'0,male,22.0,1,0,7.25,Third,unknown,Southampton,n'\n",
"b'1,female,38.0,1,0,71.2833,First,C,Cherbourg,n'\n",
"b'1,female,26.0,0,0,7.925,Third,unknown,Southampton,y'\n",
"b'1,female,35.0,1,0,53.1,First,C,Southampton,n'\n",
"b'0,male,28.0,0,0,8.4583,Third,unknown,Queenstown,y'\n",
"b'0,male,2.0,3,1,21.075,Third,unknown,Southampton,n'\n",
"b'1,female,27.0,0,2,11.1333,Third,unknown,Southampton,n'\n",
"b'1,female,14.0,1,0,30.0708,Second,unknown,Cherbourg,n'\n",
"b'1,female,4.0,1,1,16.7,Third,G,Southampton,n'\n"
]
}
],
"source": [
"# TextLineDataset产生每个文件的每一行,这可能是不希望的,例如,如果文件以标题行开头或包含注释。可以使用Dataset.skip()或 Dataset.filter()转换删除这些行。在这里,您跳过第一行,然后过滤以仅查找幸存者。\n",
"titanic_file = tf.keras.utils.get_file(\"train.csv\", \"https://storage.googleapis.com/tf-datasets/titanic/train.csv\")\n",
"titanic_lines = tf.data.TextLineDataset(titanic_file)\n",
"\n",
"for line in titanic_lines.take(10):\n",
" print(line.numpy())"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"b'1,female,38.0,1,0,71.2833,First,C,Cherbourg,n'\nb'1,female,26.0,0,0,7.925,Third,unknown,Southampton,y'\nb'1,female,35.0,1,0,53.1,First,C,Southampton,n'\nb'1,female,27.0,0,2,11.1333,Third,unknown,Southampton,n'\nb'1,female,14.0,1,0,30.0708,Second,unknown,Cherbourg,n'\nb'1,female,4.0,1,1,16.7,Third,G,Southampton,n'\nb'1,male,28.0,0,0,13.0,Second,unknown,Southampton,y'\nb'1,female,28.0,0,0,7.225,Third,unknown,Cherbourg,y'\nb'1,male,28.0,0,0,35.5,First,A,Southampton,y'\nb'1,female,38.0,1,5,31.3875,Third,unknown,Southampton,n'\n"
]
}
],
"source": [
"def survived(line):\n",
" return tf.not_equal(tf.strings.substr(line, 0, 1), \"0\")\n",
"\n",
"survivors = titanic_lines.skip(1).filter(survived)\n",
"\n",
"for line in survivors.take(10):\n",
" print(line.numpy())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}