TensorFlow 2 quickstart for experts

简介: TensorFlow 2 quickstart for experts

Import TensorFlow into your program:

import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

Load and prepare the MNIST dataset.

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

# Add a channels dimension
x_train = x_train[..., tf.newaxis].astype("float32")
x_test = x_test[..., tf.newaxis].astype("float32")

Use tf.data to batch and shuffle the dataset:

train_ds = tf.data.Dataset.from_tensor_slices(
    (x_train, y_train)).shuffle(10000).batch(32)

test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

Build the tf.keras model using the Keras model subclassing API:

class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.conv1 = Conv2D(32, 3, activation='relu')
    self.flatten = Flatten()
    self.d1 = Dense(128, activation='relu')
    self.d2 = Dense(10)

  def call(self, x):
    x = self.conv1(x)
    x = self.flatten(x)
    x = self.d1(x)
    return self.d2(x)

# Create an instance of the model
model = MyModel()

Choose an optimizer and loss function for training:

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

optimizer = tf.keras.optimizers.Adam()

Select metrics to measure the loss and the accuracy of the model. These metrics accumulate the values over epochs and then print the overall result.

train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')

Use tf.GradientTape to train the model:

@tf.function
def train_step(images, labels):
  with tf.GradientTape() as tape:
    # training=True is only needed if there are layers with different
    # behavior during training versus inference (e.g. Dropout).
    predictions = model(images, training=True)
    loss = loss_object(labels, predictions)
  gradients = tape.gradient(loss, model.trainable_variables)
  optimizer.apply_gradients(zip(gradients, model.trainable_variables))

  train_loss(loss)
  train_accuracy(labels, predictions)

Test the model:

@tf.function
def test_step(images, labels):
  # training=False is only needed if there are layers with different
  # behavior during training versus inference (e.g. Dropout).
  predictions = model(images, training=False)
  t_loss = loss_object(labels, predictions)

  test_loss(t_loss)
  test_accuracy(labels, predictions)
EPOCHS = 5for epoch in range(EPOCHS):  # Reset the metrics at the start of the next epoch  train_loss.reset_states()  train_accuracy.reset_states()  test_loss.reset_states()  test_accuracy.reset_states()  for images, labels in train_ds:    train_step(images, labels)  for test_images, test_labels in test_ds:    test_step(test_images, test_labels)  print(    f'Epoch {epoch + 1}, '    f'Loss: {train_loss.result()}, '    f'Accuracy: {train_accuracy.result() * 100}, '    f'Test Loss: {test_loss.result()}, '    f'Test Accuracy: {test_accuracy.result() * 100}'  )

The image classifier is now trained to ~98% accuracy on this dataset

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

目录
相关文章
|
1月前
|
Shell 程序员 开发者
轻松搞定在Python中构建虚拟环境
本教程教你如何使用业界公认的最佳实践,创建一个完全工作的Python开发环境。虚拟环境通过隔离依赖项,避免项目间的冲突,并允许你轻松管理包版本。我们将使用Python 3的内置`venv`模块来创建和激活虚拟环境,确保不同项目能独立运行,不会相互干扰。此外,还将介绍如何检查Python版本、激活和停用虚拟环境,以及使用`requirements.txt`文件共享依赖项。 通过本教程,你将学会: - 创建和管理虚拟环境 - 避免依赖性冲突 - 部署Python应用到服务器 适合新手和希望提升开发环境管理能力的开发者。
110 2
|
搜索推荐 数据挖掘 PyTorch
Py之albumentations:albumentations库函数的简介、安装、使用方法之详细攻略续篇
Py之albumentations:albumentations库函数的简介、安装、使用方法之详细攻略续篇
Py之albumentations:albumentations库函数的简介、安装、使用方法之详细攻略续篇
|
4月前
|
Shell 开发者 iOS开发
Python 环境搭建之 conda
本文介绍了Python项目管理工具Conda的两种版本——Anaconda和Miniconda的安装方法及环境使用,特别针对MacOS系统。Anaconda为全量版,适合新手;Miniconda则为轻量级版本,适合有经验的开发者。文中还提供了具体的安装命令和路径说明,帮助用户顺利完成安装并验证安装结果。
189 0
Python 环境搭建之 conda
|
4月前
|
机器学习/深度学习 开发者 数据格式
Gradio如何使用
**Gradio** 是一个开源 Python 库,用于快速创建和部署机器学习模型的用户界面。它支持多种输入输出形式,如文本、图像、音频等,无需复杂 Web 开发知识即可实现模型的直观展示和交互。Gradio 特点包括简单易用、实时更新、多样的输入输出形式以及轻松部署。通过几个简单的步骤,即可创建和分享功能强大的机器学习应用。
126 0
|
9月前
|
Python
【Python指南 | 第一篇】Python环境配置及pip安装教程
【Python指南 | 第一篇】Python环境配置及pip安装教程
198 1
|
TensorFlow 算法框架/工具 异构计算
YOLO实践应用之搭建开发环境(Windows系统、Python 3.8、TensorFlow2.3版本)
基于YOLO进行物体检测、对象识别,先和大家分享如何搭建开发环境,会分为CPU版本、GPU版本的两种开发环境,本文会分别详细地介绍搭建环境的过程。主要使用TensorFlow2.3、opencv-python4.4.0、Pillow、matplotlib 等依赖库。
353 0
ModelScope官方镜像,CPU环境镜像(python3.8)pull不存在
在pullModelScope官方镜像时,一直pull失败,发现官方镜像应该没有推送,Python3.7的是有的
|
数据安全/隐私保护 Python
Python 工具包发布
首先,我们可以创建一个 Python 工具包,比如叫做 mypackage,它包含一个模块 mymodule 和一个函数 hello,用于输出 Hello, world!。目录结构如下:
445 1
|
Web App开发 存储 数据可视化
【Pytorch 安装TensorboardX及使用
【Pytorch 安装TensorboardX及使用
1267 0
|
PyTorch 算法框架/工具
快速安装Pytorch
快速安装Pytorch
103 0
快速安装Pytorch

热门文章

最新文章