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

目录
相关文章
|
机器学习/深度学习 人工智能 编解码
AI人像特效之「一键生成N次元虚拟形象」
为了零成本低门槛地提供极致酷炫的人像玩法,我们提出了一套人像风格化通用框架「AI Maleonn」AI 版神笔马良,用于一键生成风格百变的人物虚拟形象,在风格上涵盖手绘、3D、日漫、艺术特效、铅笔画等多种风格,同时可以支持面向小样本的专属风格定制,利用少量目标风格图即可实现快速迁移拓展;在处理维度上,不仅适用于生成头部效果,更支持全图精细化纹理转换,兼容多人场景;在模型鲁棒性上,有效克服了多角度姿态、面部遮挡等各类复杂场景,整体稳定性大大提升。
|
机器学习/深度学习 算法 数据可视化
浅析特征数据离散化的几种方法(上)
什么是离散化? 离散化就是把无限空间中有限的个体映射到有限的空间中去,以此提高算法的时空效率。通俗的说,离散化是在不改变数据相对大小的条件下,对数据进行相应的缩小。例如:
|
11月前
|
调度 开发者 Python
异步编程在Python中的应用:Asyncio和Coroutines
【10月更文挑战第10天】本文介绍了Python中异步编程的应用,重点讲解了`asyncio`模块和协程的概念、原理及使用方法。通过一个简单的HTTP服务器示例,展示了如何利用`asyncio`和协程实现高效的并发处理。
74 1
|
Python
蛇形矩阵python
蛇形矩阵python
149 0
Proteus 8 Professional安装教程
Proteus 8 Professional安装教程
1503 0
|
DataWorks 安全 关系型数据库
DataWorks产品使用合集之如何在调度时,给同步的表添加参数
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
70 0
|
Java 数据挖掘 数据库连接
简单讲一下 python,Java,C++,C#,Go,Ruby 语言的优势和前景
python,Java,C++,C#,Go,Ruby 语言的优势和前景
简单讲一下 python,Java,C++,C#,Go,Ruby 语言的优势和前景
|
弹性计算 安全 程序员
ecs 云服务器使用体验感想
在使用了一周的ecs服务器后,我有以下感想。
ecs 云服务器使用体验感想
|
存储 弹性计算 缓存
3.1.1计算服务亚马逊 AWS|学习笔记(一)
快速学习3.1.1计算服务亚马逊 AWS
3.1.1计算服务亚马逊 AWS|学习笔记(一)
|
搜索推荐 程序员
程序员的自我修养
程序员的自我修养 10
219 0
程序员的自我修养