TensorFlow 2 quickstart for beginners

简介: This short introduction uses Keras to:1. Build a neural network that classifies images.2. Train this neural network.3. And, finally, evaluate the accuracy of the model.

This short introduction uses Keras to:

  1. Build a neural network that classifies images.
  2. Train this neural network.
  3. And, finally, evaluate the accuracy of the model.
import tensorflow as tf

Load and prepare the MNIST dataset. Convert the samples from integers to floating-point numbers:

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

Build the tf.keras.Sequential model by stacking layers. Choose an optimizer and loss function for training:

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])

For each example the model returns a vector of "logits" or "log-odds" scores, one for each class.

predictions = model(x_train[:1]).numpy()
predictions

The tf.nn.softmax function converts these logits to "probabilities" for each class:

tf.nn.softmax(predictions).numpy()

Note: It is possible to bake this tf.nn.softmax in as the activation function for the last layer of the network. While this can make the model output more directly interpretable, this approach is discouraged as it's impossible to provide an exact and numerically stable loss calculation for all models when using a softmax output.

The losses.SparseCategoricalCrossentropy loss takes a vector of logits and a True index and returns a scalar loss for each example.

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

This loss is equal to the negative log probability of the true class: It is zero if the model is sure of the correct class.

This untrained model gives probabilities close to random (1/10 for each class), so the initial loss should be close to -tf.math.log(1/10) ~= 2.3

loss_fn(y_train[:1], predictions).numpy()
model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

The Model.fit method adjusts the model parameters to minimize the loss:

model.fit(x_train, y_train, epochs=5)

The Model.evaluate method checks the models performance, usually on a "Validation-set" or "Test-set".

model.evaluate(x_test,  y_test, verbose=2)

The image classifier is now trained to ~98% accuracy on this dataset. To learn more, read the TensorFlow tutorials.

If you want your model to return a probability, you can wrap the trained model, and attach the softmax to it:

probability_model = tf.keras.Sequential([
  model,
  tf.keras.layers.Softmax()
])
probability_model(x_test[:5])

代码链接: https://codechina.csdn.net/csdn_codechina/enterprise_technology/-/blob/master/CV_Classification/TensorFlow%202%20quickstart%20for%20beginners.ipynb

目录
相关文章
|
28天前
|
并行计算 TensorFlow 算法框架/工具
tensorflow安装
tensorflow安装——GPU版
42 2
|
6月前
|
机器学习/深度学习 存储 TensorFlow
TensorFlow 2.0 快速入门指南:第三部分
TensorFlow 2.0 快速入门指南:第三部分
183 0
|
6月前
|
机器学习/深度学习 TensorFlow API
TensorFlow 2.0 快速入门指南:第一部分
TensorFlow 2.0 快速入门指南:第一部分
201 0
|
6月前
|
机器学习/深度学习 算法 TensorFlow
TensorFlow 2.0 快速入门指南:第二部分
TensorFlow 2.0 快速入门指南:第二部分
72 0
|
机器学习/深度学习 算法 Java
TensorFlow Lite介绍
TensorFlow Lite是为了解决TensorFlow在移动平台和嵌入式端过于臃肿而定制开发的轻量级解决方案,是与TensorFlow完全独立的两个项目,与TensorFlow基本没有代码共享。TensorFlow本身是为桌面和服务器端设计开发的,没有为ARM移动平台定制优化,因此如果直接用在移动平台或者嵌入式端会“水土不服”。
499 0
|
TensorFlow 算法框架/工具 开发工具
TF学习——TF之TensorFlow Slim:TensorFlow Slim的简介、安装、使用方法之详细攻略
TF学习——TF之TensorFlow Slim:TensorFlow Slim的简介、安装、使用方法之详细攻略
TF学习——TF之TensorFlow Slim:TensorFlow Slim的简介、安装、使用方法之详细攻略
|
TensorFlow 算法框架/工具 Python
成功解决tensorflow\contrib\learn\python\learn\datasets\mnist.py: maybe_download (from tensorflow.contri
成功解决tensorflow\contrib\learn\python\learn\datasets\mnist.py: maybe_download (from tensorflow.contri
|
TensorFlow API 算法框架/工具
TensorFlow 2 quickstart for experts
TensorFlow 2 quickstart for experts
185 0
|
TensorFlow 算法框架/工具 Python
TensorFlow Recommenders: Quickstart
In this tutorial, we build a simple matrix factorization model using the MovieLens 100K dataset with TFRS. We can use this model to recommend movies for a given user.
245 0
|
算法 TensorFlow 算法框架/工具
Tensorflow源码解析6 -- TensorFlow本地运行时
# 1 概述 TensorFlow后端分为四层,运行时层、计算层、通信层、设备层。运行时作为第一层,实现了session管理、graph管理等很多重要的逻辑,是十分关键的一层。根据任务分布的不同,运行时又分为本地运行时和分布式运行时。本地运行时,所有任务运行于本地同一进程内。而分布式运行时,则允许任务运行在不同机器上。 Tensorflow的运行,通过session搭建了前后端沟通的桥
3170 0