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

目录
相关文章
|
存储 Java 数据库连接
MyBatis-Plus 基础操作指南:实现高效的增删改查
MyBatis-Plus 基础操作指南:实现高效的增删改查
798 0
|
网络安全 容器
SSH——ssh: rejected: administratively prohibited (open failed)
SSH——ssh: rejected: administratively prohibited (open failed)
474 0
|
11月前
|
监控 关系型数据库 MySQL
一次彻底讲清如何处理mysql 的死锁问题
【10月更文挑战第16天】本文详细介绍了如何处理 MySQL 中的死锁问题,涵盖死锁的概念、原因、检测方法及解决策略,强调通过优化事务设计、调整数据库参数、手动处理和预防措施等手段,有效减少死锁,提升数据库性能与稳定性。
2008 0
人脸关键点识别
【6月更文挑战第21天】
88 4
人脸关键点识别
|
机器学习/深度学习 人工智能 数据处理
人工智能平台PAI产品使用合集之最大长度是指的是batch内最长序列吗
阿里云人工智能平台PAI是一个功能强大、易于使用的AI开发平台,旨在降低AI开发门槛,加速创新,助力企业和开发者高效构建、部署和管理人工智能应用。其中包含了一系列相互协同的产品与服务,共同构成一个完整的人工智能开发与应用生态系统。以下是对PAI产品使用合集的概述,涵盖数据处理、模型开发、训练加速、模型部署及管理等多个环节。
|
消息中间件 Java 数据库连接
实时计算 Flink版产品使用合集之将sdkMode从rpc模式改为jdbc模式后,table.exec.mini-batch.enabled参数还生效吗
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
151 0
|
开发工具 git
Git恢复之前版本的两种方法reset、revert(图文详解)
Git恢复之前版本的两种方法reset、revert(图文详解)
1098 0
|
机器学习/深度学习 编解码 人工智能
高效轻量级语义分割综述
语义分割是自动驾驶中视觉理解的重要组成部分。然而当前SOTA的模型都非常复杂和繁琐,因此不适合部署在计算资源受限且耗时要求较低的车载芯片平台上。本文深入研究了更紧凑、更高效的模型以解决上述问题,这些模型能够部署在低内存嵌入式系统上,同时满足实时推理的需求。本文讨论了该领域一些优秀的工作,根据它们的主要贡献进行归类,最后本文评估了在相同软硬件条件下模型的推理速度,这些条件代表了一个典型的高性能GPU和低内存嵌入式GPU的实际部署场景。本文的实验结果表明,许多工作能够在资源受限的硬件上实现性能和耗时的平衡。
高效轻量级语义分割综述
|
存储 SQL 自然语言处理
MySQL 模糊查询再也不用like+%了
MySQL 模糊查询再也不用like+%了
MySQL 模糊查询再也不用like+%了
|
关系型数据库 MySQL 数据库