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

目录
相关文章
【图像分类数据集】非常全面实用的垃圾分类图片数据集共享
【图像分类数据集】非常全面实用的垃圾分类图片数据集共享
2310 38
【图像分类数据集】非常全面实用的垃圾分类图片数据集共享
|
存储 Ubuntu C语言
Ubuntu 软件安装方法(入门必看)
Ubuntu 软件安装方法(入门必看)
1444 0
Ubuntu 软件安装方法(入门必看)
|
9月前
|
人工智能 JSON 机器人
阿里云轻量服务器OpenClaw一键部署+Slack无缝接入流程+避坑指南
阿里云轻量应用服务器为OpenClaw提供预装镜像与一键部署能力,无需手动配置依赖环境,是新手快速搭建稳定AI助手的最优选择。本文从部署准备、轻量服务器实例创建、OpenClaw基础配置、Slack接入、阿里云百炼免费大模型API配置到常见问题解答,全程覆盖,所有命令可直接复制执行,助力零基础用户快速搭建OpenClaw服务并接入Slack,实现消息自动回复、指令执行等功能。
462 2
|
9月前
|
存储 安全 编译器
从机器码到逻辑之美:汇编语言深度透视
本文深入浅出地解析X86汇编核心:从寄存器(EAX/EBP/ESP等)的职能与分层,到栈帧构建、CALL/RET机制与调用约定;涵盖寻址模式、MOV/LEA差异、标志位(ZF/CF/SF)控制流、保护模式与系统调用,并延伸至64位演进、SIMD加速、栈溢出原理及调试断点本质。全篇以物理视角揭示程序运行真相——汇编是连接人类逻辑与硅基世界的终极桥梁。(239字)
1053 0
|
9月前
|
人工智能 物联网 C++
深耕多领域,赋能新科技——C++的核心运用与时代价值
自1983年诞生以来,C++语言凭借高效的执行性能、灵活的内存控制和强大的兼容性,历经四十余年迭代,始终在编程语言领域占据核心地位。
563 0
|
11月前
|
弹性计算 人工智能 小程序
阿里云服务器多少钱一年?2026年最新曝光,包括轻量、ECS和GPU云服务器价格清单
阿里云2026年服务器价格揭晓:轻量应用服务器低至¥38/年,ECS云服务器新购续费同价,GPU服务器支持大模型训练。涵盖个人建站、企业应用与AI计算,三类机型全解析,助你选型不花冤枉钱。
955 3
|
12月前
|
小程序 机器人 开发工具
飞书文档自动更新到百炼知识库
计算巢AppFlow支持定时自动同步飞书文档至百炼知识库,实现RAG检索。通过创建飞书应用、配置权限与凭证,结合AppFlow流程模板,可高效完成知识库自动化更新,大幅降低人工维护成本。
1619 4
|
人工智能
ICLR 2025 | 中科院+哈工大重磅发现:预训练视觉模型分类越准,可解释性越强
中科院、哈工大等团队在ICLR 2025发表研究,提出“内在可解释性评分”(IIS),发现预训练视觉模型分类越准,可解释性越强。通过IIS量化可解释性,实验证明高分类性能与高可解释性可兼得,甚至相互促进,打破传统认知。
378 0
|
数据采集 弹性计算 供应链
阿里云服务器付费模式:按量付费、包年包月和抢占式实例全解析
阿里云服务器提供包年包月、按量付费与抢占式实例三种付费模式。包年包月为预付费,适合长期稳定使用,价格更优惠并支持备案。按量付费则为后付费模式,按小时结算,适合短期或访问量波动大的场景,但不支持备案。抢占式实例基于按量付费,价格更低(最多节省90%),适用于无状态应用,如临时测试或可弹性伸缩的Web服务,但存在被系统释放的风险,同样不支持备案。根据具体需求选择合适的付费模式能够有效降低成本并提高效率。
1210 1
|
网络协议 安全 算法
RIP两个版本:RIP-1和RIP-2
【7月更文挑战第14天】
901 0
RIP两个版本:RIP-1和RIP-2