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

目录
相关文章
|
7月前
|
人工智能 JSON 机器人
阿里云轻量服务器OpenClaw一键部署+Slack无缝接入流程+避坑指南
阿里云轻量应用服务器为OpenClaw提供预装镜像与一键部署能力,无需手动配置依赖环境,是新手快速搭建稳定AI助手的最优选择。本文从部署准备、轻量服务器实例创建、OpenClaw基础配置、Slack接入、阿里云百炼免费大模型API配置到常见问题解答,全程覆盖,所有命令可直接复制执行,助力零基础用户快速搭建OpenClaw服务并接入Slack,实现消息自动回复、指令执行等功能。
427 2
|
7月前
|
存储 安全 编译器
从机器码到逻辑之美:汇编语言深度透视
本文深入浅出地解析X86汇编核心:从寄存器(EAX/EBP/ESP等)的职能与分层,到栈帧构建、CALL/RET机制与调用约定;涵盖寻址模式、MOV/LEA差异、标志位(ZF/CF/SF)控制流、保护模式与系统调用,并延伸至64位演进、SIMD加速、栈溢出原理及调试断点本质。全篇以物理视角揭示程序运行真相——汇编是连接人类逻辑与硅基世界的终极桥梁。(239字)
942 0
|
9月前
|
弹性计算 人工智能 小程序
阿里云服务器多少钱一年?2026年最新曝光,包括轻量、ECS和GPU云服务器价格清单
阿里云2026年服务器价格揭晓:轻量应用服务器低至¥38/年,ECS云服务器新购续费同价,GPU服务器支持大模型训练。涵盖个人建站、企业应用与AI计算,三类机型全解析,助你选型不花冤枉钱。
854 3
|
10月前
|
小程序 机器人 开发工具
飞书文档自动更新到百炼知识库
计算巢AppFlow支持定时自动同步飞书文档至百炼知识库,实现RAG检索。通过创建飞书应用、配置权限与凭证,结合AppFlow流程模板,可高效完成知识库自动化更新,大幅降低人工维护成本。
1428 4
|
10月前
|
人工智能
ICLR 2025 | 中科院+哈工大重磅发现:预训练视觉模型分类越准,可解释性越强
中科院、哈工大等团队在ICLR 2025发表研究,提出“内在可解释性评分”(IIS),发现预训练视觉模型分类越准,可解释性越强。通过IIS量化可解释性,实验证明高分类性能与高可解释性可兼得,甚至相互促进,打破传统认知。
317 0
|
XML 前端开发 JavaScript
JSX是什么
【8月更文挑战第28天】JSX是什么
1072 63
|
网络协议 安全 算法
RIP两个版本:RIP-1和RIP-2
【7月更文挑战第14天】
868 0
RIP两个版本:RIP-1和RIP-2
|
存储 算法 安全
深入理解汇编语言:基础语法和常用指令介绍
深入理解汇编语言:基础语法和常用指令介绍
1248 1
|
SQL 关系型数据库 MySQL
深入探索MySQL SELECT查询:从基础到高级,解锁数据宝藏的密钥
深入探索MySQL SELECT查询:从基础到高级,解锁数据宝藏的密钥

热门文章

最新文章