提交 6b9f1d6d 编写于 作者: M MaoXianxin

tensorflow

上级 265af8d8
......@@ -6,3 +6,13 @@ Git简介.md
code china社区云.md
others/日文版蓝皮书宣传.md
others/科创中国 2021 年度开源创新榜单评选.md
code china tutorial/new project.md
others/20210804-CSDN“开源服务加速计划”是什么\? 开源技术栈选型Show回顾.md
others/explore页面.md
others/IT开源知识图谱.md
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"import datetime\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 2,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Num GPUs Availabel: 1\n"
]
}
],
"source": [
"print(\"Num GPUs Availabel: \", len(tf.config.list_physical_devices('GPU')))"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 3,
"outputs": [
{
"data": {
"text/plain": "[PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'),\n PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]"
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tf.config.list_physical_devices()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 4,
"outputs": [
{
"data": {
"text/plain": "[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]"
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tf.config.list_physical_devices('GPU')"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 5,
"outputs": [],
"source": [
"physical_devices = tf.config.list_physical_devices('GPU')"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 6,
"outputs": [],
"source": [
"try:\n",
" tf.config.set_visible_devices(physical_devices[0], 'GPU')\n",
" logical_devices = tf.config.list_physical_devices('GPU')\n",
" assert len(logical_devices) == len(physical_devices)\n",
"except:\n",
" pass"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 7,
"outputs": [],
"source": [
"mnist = tf.keras.datasets.mnist"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 8,
"outputs": [],
"source": [
"(x_train, y_train), (x_test, y_test) = mnist.load_data()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 9,
"outputs": [
{
"data": {
"text/plain": "(255, 0)"
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.max(x_train), np.min(x_train)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 10,
"outputs": [],
"source": [
"x_train, x_test = x_train / 255.0, x_test / 255.0"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 11,
"outputs": [],
"source": [
"def create_model():\n",
" return tf.keras.models.Sequential([\n",
" tf.keras.layers.Flatten(input_shape=(28, 28)),\n",
" tf.keras.layers.Dense(512, activation='relu'),\n",
" tf.keras.layers.Dropout(0.2),\n",
" tf.keras.layers.Dense(10, activation='softmax')\n",
" ])"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 12,
"outputs": [],
"source": [
"model = create_model()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 13,
"outputs": [],
"source": [
"model.compile(optimizer='adam',\n",
" loss='sparse_categorical_crossentropy',\n",
" metrics=['accuracy'])"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 14,
"outputs": [],
"source": [
"log_dir = 'logs/fit/' + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 15,
"outputs": [],
"source": [
"tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 16,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1/12\n",
"1875/1875 - 4s - loss: 0.2200 - accuracy: 0.9364 - val_loss: 0.1080 - val_accuracy: 0.9652\n",
"Epoch 2/12\n",
"1875/1875 - 4s - loss: 0.0968 - accuracy: 0.9697 - val_loss: 0.0849 - val_accuracy: 0.9739\n",
"Epoch 3/12\n",
"1875/1875 - 5s - loss: 0.0686 - accuracy: 0.9786 - val_loss: 0.0704 - val_accuracy: 0.9776\n",
"Epoch 4/12\n",
"1875/1875 - 2s - loss: 0.0520 - accuracy: 0.9829 - val_loss: 0.0698 - val_accuracy: 0.9790\n",
"Epoch 5/12\n",
"1875/1875 - 2s - loss: 0.0431 - accuracy: 0.9858 - val_loss: 0.0727 - val_accuracy: 0.9785\n",
"Epoch 6/12\n",
"1875/1875 - 2s - loss: 0.0349 - accuracy: 0.9881 - val_loss: 0.0722 - val_accuracy: 0.9797\n",
"Epoch 7/12\n",
"1875/1875 - 4s - loss: 0.0336 - accuracy: 0.9885 - val_loss: 0.0654 - val_accuracy: 0.9826\n",
"Epoch 8/12\n",
"1875/1875 - 2s - loss: 0.0274 - accuracy: 0.9908 - val_loss: 0.0675 - val_accuracy: 0.9806\n",
"Epoch 9/12\n",
"1875/1875 - 2s - loss: 0.0233 - accuracy: 0.9919 - val_loss: 0.0719 - val_accuracy: 0.9811\n",
"Epoch 10/12\n",
"1875/1875 - 3s - loss: 0.0238 - accuracy: 0.9920 - val_loss: 0.0666 - val_accuracy: 0.9824\n",
"Epoch 11/12\n",
"1875/1875 - 4s - loss: 0.0199 - accuracy: 0.9936 - val_loss: 0.0721 - val_accuracy: 0.9838\n",
"Epoch 12/12\n",
"1875/1875 - 3s - loss: 0.0170 - accuracy: 0.9940 - val_loss: 0.0751 - val_accuracy: 0.9817\n"
]
},
{
"data": {
"text/plain": "<tensorflow.python.keras.callbacks.History at 0x7f60550f01d0>"
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.fit(x=x_train,\n",
" y=y_train,\n",
" epochs=12,\n",
" validation_data=(x_test, y_test),\n",
" callbacks=[tensorboard_callback],\n",
" verbose=2)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 16,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
\ No newline at end of file
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Num GPUs Available: 1\n"
]
}
],
"source": [
"import tensorflow as tf\n",
"import datetime\n",
"\n",
"print(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n",
"\n",
"physical_devices = tf.config.list_physical_devices('GPU')\n",
"try:\n",
" # Disable first GPU\n",
" tf.config.set_visible_devices(physical_devices[0], 'GPU')\n",
" logical_devices = tf.config.list_logical_devices('GPU')\n",
" # Logical device was not created for first GPU\n",
" assert len(logical_devices) == len(physical_devices)\n",
"except:\n",
" # Invalid device or cannot modify virtual devices once initialized.\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": 2,
"outputs": [],
"source": [
"mnist = tf.keras.datasets.mnist\n",
"\n",
"(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
"x_train, x_test = x_train / 255.0, x_test / 255.0"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 3,
"outputs": [],
"source": [
"AUTOTUNE = tf.data.AUTOTUNE\n",
"\n",
"train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n",
"test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n",
"\n",
"train_dataset = train_dataset.shuffle(60000).batch(64)\n",
"test_dataset = test_dataset.batch(64)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 4,
"outputs": [],
"source": [
"loss_object = tf.keras.losses.SparseCategoricalCrossentropy()\n",
"optimizer = tf.keras.optimizers.Adam()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 5,
"outputs": [],
"source": [
"train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)\n",
"train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('train_accuracy')\n",
"test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32)\n",
"test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('test_accuracy')"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 6,
"outputs": [],
"source": [
"def train_step(model, optimizer, x_train, y_train):\n",
" with tf.GradientTape() as tape:\n",
" predictions = model(x_train, training=True)\n",
" loss = loss_object(y_train, predictions)\n",
" grads = tape.gradient(loss, model.trainable_variables)\n",
" optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
"\n",
" train_loss(loss)\n",
" train_accuracy(y_train, predictions)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 7,
"outputs": [],
"source": [
"def test_step(model, x_test, y_test):\n",
" predictions = model(x_test)\n",
" loss = loss_object(y_test, predictions)\n",
"\n",
" test_loss(loss)\n",
" test_accuracy(y_test, predictions)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 8,
"outputs": [],
"source": [
"current_time = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n",
"train_log_dir = 'logs/gradient_tape/' + current_time + '/train'\n",
"test_log_dir = 'logs/gradient_tape/' + current_time + '/test'\n",
"train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n",
"test_summary_writer = tf.summary.create_file_writer(test_log_dir)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 9,
"outputs": [],
"source": [
"def create_model():\n",
" return tf.keras.models.Sequential([\n",
" tf.keras.layers.Flatten(input_shape=(28, 28)),\n",
" tf.keras.layers.Dense(512, activation='relu'),\n",
" tf.keras.layers.Dropout(0.2),\n",
" tf.keras.layers.Dense(10, activation='softmax')\n",
" ])"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 10,
"outputs": [],
"source": [
"model = create_model()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 11,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 1, Loss: 0.24552594125270844, Accuracy: 92.82833099365234, Test Loss: 0.1183900311589241, Test Accuracy: 96.4800033569336\n",
"Epoch 2, Loss: 0.10400832444429398, Accuracy: 96.8316650390625, Test Loss: 0.09798828512430191, Test Accuracy: 97.0199966430664\n",
"Epoch 3, Loss: 0.07136962562799454, Accuracy: 97.836669921875, Test Loss: 0.06859268248081207, Test Accuracy: 97.93000030517578\n",
"Epoch 4, Loss: 0.0560942105948925, Accuracy: 98.23833465576172, Test Loss: 0.0651865303516388, Test Accuracy: 97.94999694824219\n",
"Epoch 5, Loss: 0.0432845763862133, Accuracy: 98.61833190917969, Test Loss: 0.06194380670785904, Test Accuracy: 98.11000061035156\n",
"Epoch 6, Loss: 0.03632642328739166, Accuracy: 98.81500244140625, Test Loss: 0.06103438511490822, Test Accuracy: 98.04999542236328\n",
"Epoch 7, Loss: 0.02910703979432583, Accuracy: 99.05166625976562, Test Loss: 0.0594552718102932, Test Accuracy: 98.18000030517578\n",
"Epoch 8, Loss: 0.026429103687405586, Accuracy: 99.14833068847656, Test Loss: 0.05901149660348892, Test Accuracy: 98.18000030517578\n",
"Epoch 9, Loss: 0.021958693861961365, Accuracy: 99.27166748046875, Test Loss: 0.06494490802288055, Test Accuracy: 98.20999908447266\n",
"Epoch 10, Loss: 0.02058562822639942, Accuracy: 99.32333374023438, Test Loss: 0.06891714036464691, Test Accuracy: 98.16999816894531\n",
"Epoch 11, Loss: 0.018852131441235542, Accuracy: 99.3933334350586, Test Loss: 0.06819362193346024, Test Accuracy: 98.22000122070312\n",
"Epoch 12, Loss: 0.016921166330575943, Accuracy: 99.43666076660156, Test Loss: 0.06820426881313324, Test Accuracy: 98.25999450683594\n",
"Epoch 13, Loss: 0.015440980903804302, Accuracy: 99.46666717529297, Test Loss: 0.07115372270345688, Test Accuracy: 98.18000030517578\n",
"Epoch 14, Loss: 0.012071464210748672, Accuracy: 99.59833526611328, Test Loss: 0.06296975165605545, Test Accuracy: 98.47000122070312\n",
"Epoch 15, Loss: 0.014436731114983559, Accuracy: 99.53166961669922, Test Loss: 0.0756523534655571, Test Accuracy: 98.31999969482422\n",
"Epoch 16, Loss: 0.013015450909733772, Accuracy: 99.5816650390625, Test Loss: 0.06969759613275528, Test Accuracy: 98.3699951171875\n",
"Epoch 17, Loss: 0.010141783393919468, Accuracy: 99.65333557128906, Test Loss: 0.07619375735521317, Test Accuracy: 98.33999633789062\n",
"Epoch 18, Loss: 0.012141303159296513, Accuracy: 99.58833312988281, Test Loss: 0.06561162322759628, Test Accuracy: 98.41999816894531\n",
"Epoch 19, Loss: 0.009175603277981281, Accuracy: 99.67666625976562, Test Loss: 0.07204129546880722, Test Accuracy: 98.31999969482422\n",
"Epoch 20, Loss: 0.011469615623354912, Accuracy: 99.63166809082031, Test Loss: 0.06824246048927307, Test Accuracy: 98.22999572753906\n"
]
}
],
"source": [
"EPOCHS = 20\n",
"\n",
"for epoch in range(EPOCHS):\n",
" for (x_train, y_train) in train_dataset:\n",
" train_step(model, optimizer, x_train, y_train)\n",
" with train_summary_writer.as_default():\n",
" tf.summary.scalar('loss', train_loss.result(), step=epoch)\n",
" tf.summary.scalar('accuracy', train_accuracy.result(), step=epoch)\n",
"\n",
" for (x_test, y_test) in test_dataset:\n",
" test_step(model, x_test, y_test)\n",
" with test_summary_writer.as_default():\n",
" tf.summary.scalar('loss', test_loss.result(), step=epoch)\n",
" tf.summary.scalar('accuracy', test_accuracy.result(), step=epoch)\n",
"\n",
" template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'\n",
" print(template.format(epoch + 1,\n",
" train_loss.result(),\n",
" train_accuracy.result() * 100,\n",
" test_loss.result(),\n",
" test_accuracy.result() * 100))\n",
"\n",
" # Reset metrics every epoch\n",
" train_loss.reset_states()\n",
" test_loss.reset_states()\n",
" train_accuracy.reset_states()\n",
" test_accuracy.reset_states()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 11,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
\ No newline at end of file
# tf.config.list_physical_devices
Return a list of physical devices visible to the host runtime.
Physical devices are hardware devices present on the host machine. By default all discovered CPU and GPU devices are considered visible.
This API allows querying the physical hardware resources prior to runtime initialization. Thus, giving an opportunity to call any additional configuration APIs. This is in contrast to tf.config.list_logical_devices, which triggers runtime initialization in order to list the configured devices.
The following example lists the number of visible GPUs on the host.
```
physical_devices = tf.config.list_physical_devices('GPU')
print("Num GPUs:", len(physical_devices))
```
However, the number of GPUs available to the runtime may change during runtime initialization due to marking certain devices as not visible or configuring multiple logical devices.
# tf.config.set_visible_devices
Set the list of visible devices.
Specifies which PhysicalDevice objects are visible to the runtime. TensorFlow will only allocate memory and place operations on visible physical devices, as otherwise no LogicalDevice will be created on them. By default all discovered devices are marked as visible.
The following example demonstrates disabling the first GPU on the machine
```
physical_devices = tf.config.list_physical_devices('GPU')
try:
# Disable first GPU
tf.config.set_visible_devices(physical_devices[1:], 'GPU')
logical_devices = tf.config.list_logical_devices('GPU')
# Logical device was not created for first GPU
assert len(logical_devices) == len(physical_devices) - 1
except:
# Invalid device or cannot modify virtual devices once initialized.
pass
```
# tf.config.list_logical_devices
Return a list of logical devices created by runtime
Logical devices may correspond to physical devices or remote devices in the cluster. Operations and tensors may be placed on these devices by using the name of the tf.config.LogicalDevice.
Calling tf.config.list_logical_devices triggers the runtime to configure any tf.config.PhysicalDevice visible to the runtime, thereby preventing further configuration. To avoid runtime initialization, call tf.config.list_physical_devices instead.
```
logical_devices = tf.config.list_logical_devices('GPU')
if len(logical_devices) > 0:
# Allocate on GPU:0
with tf.device(logical_devices[0].name):
one = tf.constant(1)
# Allocate on GPU:1
with tf.device(logical_devices[1].name):
two = tf.constant(2)
```
In machine learning, to improve something you often need to be able to measure it. TensorBoard is a tool for providing the measurements and visualizations needed during the machine learning workflow. It enables tracking experiment metrics like loss and accuracy, visualizing the model graph, projecting embeddings to a lower dimensional space, and much more.
Using the MNIST dataset as the example, normalize the data and write a function that creates a simple Keras model for classifying the images into 10 classes.
```
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
```
When training with Keras's Model.fit(), adding the tf.keras.callbacks.TensorBoard callback ensures that logs are created and stored. Additionally, enable histogram computation every epoch with histogram_freq=1 (this is off by default)
Place the logs in a timestamped subdirectory to allow easy selection of different training runs.
```
model = create_model()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tensorboard_callback])
```
![](https://maoxianxin1996.oss-accelerate.aliyuncs.com/codechina1/20210807200805.png)
![](https://maoxianxin1996.oss-accelerate.aliyuncs.com/codechina1/20210807200823.png)
A brief overview of the dashboards shown (tabs in top navigation bar):
- The **Scalars** dashboard shows how the loss and metrics change with every epoch. You can use it to also track training speed, learning rate, and other scalar values.
- The **Graphs** dashboard helps you visualize your model. In this case, the Keras graph of layers is shown which can help you ensure it is built correctly.
- The **Distributions** and **Histograms** dashboards show the distribution of a Tensor over time. This can be useful to visualize weights and biases and verify that they are changing in an expected way.
Additional TensorBoard plugins are automatically enabled when you log other types of data. For example, the Keras TensorBoard callback lets you log images and embeddings as well. You can see what other plugins are available in TensorBoard by clicking on the "inactive" dropdown towards the top right
x_train.shape = (60000, 28, 28)
min = 0
max = 255
y_train.shape = (60000,)
min = 0
max = 9
```
x_train, x_test = x_train / 255.0, y_test / 255.0
对数据进行MinMaxScaler(),缩放到[0,1]
作用:
加快学习算法的收敛速度
使不同量纲的特征处于同一数值量级,减少方差大的特征的影响,使模型更准确
```
\ No newline at end of file
When training with methods such as tf.GradientTape(), use tf.summary to log the required information.
Use the same dataset as above, but convert it to tf.data.Dataset to take advantage of batching capabilities:
```
import tensorflow as tf
import datetime
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
physical_devices = tf.config.list_physical_devices('GPU')
try:
# Disable first GPU
tf.config.set_visible_devices(physical_devices[:1], 'GPU')
logical_devices = tf.config.list_logical_devices('GPU')
# Logical device was not created for first GPU
assert len(logical_devices) == len(physical_devices) - 1
except:
# Invalid device or cannot modify virtual devices once initialized.
pass
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
AUTOTUNE = tf.data.AUTOTUNE
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))
train_dataset = train_dataset.shuffle(60000).batch(64)
test_dataset = test_dataset.batch(64)
```
The training code follows the advanced quickstart tutorial, but shows how to log metrics to TensorBoard. Choose loss and optimizer:
```
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
```
Create stateful metrics that can be used to accumulate values during training and logged at any point:
```
# Define our metrics
train_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('train_accuracy')
test_loss = tf.keras.metrics.Mean('test_loss', dtype=tf.float32)
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('test_accuracy')
```
Define the training and test functions:
```
def train_step(model, optimizer, x_train, y_train):
with tf.GradientTape() as tape:
predictions = model(x_train, training=True)
loss = loss_object(y_train, predictions)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_loss(loss)
train_accuracy(y_train, predictions)
def test_step(model, x_test, y_test):
predictions = model(x_test)
loss = loss_object(y_test, predictions)
test_loss(loss)
test_accuracy(y_test, predictions)
```
Set up summary writers to write the summaries to disk in a different logs directory:
```
current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
train_log_dir = 'logs/gradient_tape/' + current_time + '/train'
test_log_dir = 'logs/gradient_tape/' + current_time + '/test'
train_summary_writer = tf.summary.create_file_writer(train_log_dir)
test_summary_writer = tf.summary.create_file_writer(test_log_dir)
```
Start training. Use tf.summary.scalar() to log metrics (loss and accuracy) during training/testing within the scope of the summary writers to write the summaries to disk. You have control over which metrics to log and how often to do it. Other tf.summary functions enable logging other types of data.
```
model = create_model() # reset our model
EPOCHS = 5
for epoch in range(EPOCHS):
for (x_train, y_train) in train_dataset:
train_step(model, optimizer, x_train, y_train)
with train_summary_writer.as_default():
tf.summary.scalar('loss', train_loss.result(), step=epoch)
tf.summary.scalar('accuracy', train_accuracy.result(), step=epoch)
for (x_test, y_test) in test_dataset:
test_step(model, x_test, y_test)
with test_summary_writer.as_default():
tf.summary.scalar('loss', test_loss.result(), step=epoch)
tf.summary.scalar('accuracy', test_accuracy.result(), step=epoch)
template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
print (template.format(epoch+1,
train_loss.result(),
train_accuracy.result()*100,
test_loss.result(),
test_accuracy.result()*100))
# Reset metrics every epoch
train_loss.reset_states()
test_loss.reset_states()
train_accuracy.reset_states()
test_accuracy.reset_states()
```
TensorBoard.dev is a free public service that enables you to upload your TensorBoard logs and get a permalink that can be shared with everyone in academic papers, blog posts, social media, etc. This can enable better reproducibility and collaboration
To use TensorBoard.dev, run the following command:
```
!tensorboard dev upload \
--logdir logs/fit \
--name "(optional) My latest experiment" \
--description "(optional) Simple comparison of several hyperparameters" \
--one_shot
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册