jetson AI course(待更新)

第一篇

从官网下载
课程网址

配置交换区,查看交换区的大小,将1GB的转变为4GB
在这里插入图片描述

sudo  vi /etc/fstab

在末尾添加swap的内容
在这里插入图片描述
重启后查看free -m
swap分区变为4GB。

第二篇

如何远程登录jetson nano和运行一个Docker容器来访问jupyterlab和课程的笔记。测试相机。

十分钟构建一个网络

google colab的代码
需要翻墙,可以自行运行无需翻墙的部分。

from IPython.display import YouTubeVideo
YouTubeVideo('cNxadbrN_aI')

一个YouTube的视频,介绍最初的视觉
以tensorflow为例,构建一个神经网络。

检查环境


import tensorflow as tf
tf.config.list_physical_devices('GPU')

这篇教程选择的示例就是tensorflow官网的fashion mnist数据集。.
在这里插入图片描述
这是图片的展示。fashion在该库有内置。
下面我们来导入数据,并将其切分为训练集和测试集。训练集来教会网络识别一些图片,测试集来检测机器的学习水平。标签就是标准答案,机器学习训练给出的结果是其给出的答案。我们要让机器给出的答案和真实的误差尽可能的小。

导入数据和显示

fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (valid_images, valid_labels) = fashion_mnist.load_data()
print(train_images.shape,valid_images.shape)

查看一下图像图像的数量和每张图的大小。
在这里插入图片描述

从我们的train_images和train_labels开始。 Train_images就像我们的抽认卡上的问题一样,Train_Labels就像答案一样。通常,数据科学家通常将此答案称为标签。 我们可以绘制这些图像之一,以查看它的外观。为此,我们将使用matplotlib。

import matplotlib.pyplot as plt

# The question number to study with. Feel free to change up to 59999.
#显示一个索引为42,即第43张(默认从0开始计数)
data_idx = 42
#创建一个图像的,使用灰度显示,添加颜色条
plt.figure()
plt.imshow(train_images[data_idx], cmap='gray')
plt.colorbar()
plt.grid(False)
plt.show()

下面是可以分别的种类。

LabelDescription
0T-shirt/top
1Trouser
2Pullover
3Dress
4Coat
5Sandal
6Shirt
7Sneaker
8Bag
9Ankle boot
train_labels[data_idx]

9
检查刚刚图片对应的标签的值是多少。对应的字典是靴子
接下来检查,验证集的图片和标签


import matplotlib.pyplot as plt

# The question number to quiz with. Feel free to change up to 9999.
data_idx = 6174

plt.figure()
plt.imshow(valid_images[data_idx], cmap='gray')
plt.colorbar()
plt.grid(False)
plt.show()
valid_labels[data_idx]

在这里插入图片描述

建立一个神经元

我们可以分解将神经元分为3个步骤:

  • 定义架构
  • 直接培训
  • 评估模型

Biological neurons tr神经元会像机器的摩斯码一样传播信息,接收电信号,在正确的条件下发送电脉冲给终端.
The Math
Computers are built with discrete 0s and 1s whereas humans and animals are built on more continuous building blocks. Because of this, some of the first neurons attempted to mimic biological neurons with a linear regression function: y = mx + b. The x is like information coming in through the dendrites and the y is like the output through the terminals. As the computer guesses more and more answers to the questions we present it, it will update its variables (m and b) to better fit the line to the data it has seen.
计算机是离散的而生物是连续的。科学家尝试通过线性回归来模仿神经元。x是上一个神经元的输入,y是给下一个神经元的输出。我们将会通过某种手段来修改神经元结构即参数m,b的值,来做出决策。

Neurons are often exposed to multivariate data. We’re going to build a neuron that takes each pixel value (which is between 0 and 255), and assign it a weight, which is equivalent to our m. Data scientists often express this weight as w. For example, the first pixel will have a weight of w0, the second will have a weight of w1, and so on. Our full equation becomes y = w0x0 + w1x1 + w2x2 + … + b.
一个神经元的上一级可能有多个值,每个连接的强度不同,所以参数不同(即权重),其次,对于本身,有一个基础的值。

Each image is 28 pixels by 28 pixels, so we will have a total of 784 weights. A pixel value of 0 would be black and a pixel value of 255 would be white. Let’s look at the raw pixel values of the previous image we plotted. Each number below will be assigned a weight.
我们使用28*28的图片,通过最简单的无图像位置信息的形式来进行推测。

#查看这个数组
valid_images[data_idx]

还有一件事要考虑:y = mx + b的输出是一个数字,但是在这里,我们试图对不同的服装进行分类。我们如何将数字转换为类别? 这是一种简单的方法:我们可以制作十个神经元,每件衣服。如果分配给“裤子”(标签#1)的神经元与其他神经元相比具有最高的输出,则该模型将为给定的输入图像猜测“裤子”。 Keras是已集成到TensorFlow中的深度学习框架,使得这样的模型易于构建。我们将使用顺序API,该API允许我们堆叠层,即通过网络馈送数据,我们将应用于数据的操作列表。
在下面的模型中,
我们有两个层:
Flatten-将多维数据转换为1维数据(例如:列表列表中的单个列表)。
Dense密集层 - 神经元的“行”。每个输入的每个神经元都有一个重量(W)。在下面的示例中,我们使用数字10放置十个神经元。 我们还将定义一个Input_shape,即我们数据的尺寸。在这种情况下,每个图像的28x28像素。
将这个标签统一为10。

number_of_classes = train_labels.max() + 1
number_of_classes
model = tf.keras.Sequential([
#定义模型输入拉伸为28*28的行
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    #进行分类,设置下一个层为10
    tf.keras.layers.Dense(number_of_classes)
])
#验证模型
model.summary()

在这里插入图片描述

下面我们将对参数数量进行分析。
对于28*28为784个像素,链接十个出神经元,每个像素对应每个神经元的连接都有权重信息。以一个为例,y = w0x0 + w1x1 + w2x2 + … +w784x784+ b.在加上一个额外的偏执权重。为785.总共十个神经元。
所以总的参数个数为7850.

image_height = 28
image_width = 28

number_of_weights = image_height * image_width * number_of_classes
number_of_weights

7840
So our weights make up 7,840 parameters. Where do the other ten come from? It’s each of the 10 neurons biases, the b in y = mx + b.

可以使用plot来显示模型

tf.keras.utils.plot_model(model, show_shapes=True)

在这里插入图片描述
此处推荐了一个工具,可以用来绘制神经网络的简图
绘制神经网络概念示意图的网站
在这里插入图片描述
目前只能绘制FCNN型的,可以初始化随机参数,来显示一个网络。
在这里插入图片描述

初始化训练

(sparse)稀疏 - 对于此功能,它指的是我们的标签是我们类别的整数索引
Categorical分类 - 此功能是用于分类的
Crossentropy交叉熵- 我们的模型越有信心,当它做出不正确的猜测时,其得分就会越好。如果模型在错误时100%自信,则它将具有负无穷大的分数!
from_logits-线性输出将转换为概率,可以将其解释为模型的信心,即特定类别是给定输入的正确类别的概率。
这种类型的损耗函数对我们的情况很好地效果很好,因为它同时对每个神经元进行分级。如果我们所有的神经元都有强烈的信号表明它们是正确的标签,我们需要一种方法来告诉他们他们不能全部正确。 对于我们的人类,我们可以添加其他指标来监视模型的学习程度。例如,也许损失很低,但是如果准确性不高,该怎么办?

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

评估模型.
fit函数可以帮助我们训练和测试模型

history = model.fit(
    train_images,
    train_labels,
    epochs=5,
    #verbose应该是是否给出训练过程的描述
    verbose=True,
    validation_data=(valid_images, valid_labels)
)

预测

是时候毕业我们的模型,让它进入现实世界。我们可以使用预测方法在一组图像上查看模型的输出,无论它们是否在原始数据集中。 请注意,KERAS在做出预测时期望有批次或多个数据点。为了对单个数据点进行预测,应将其转换为一个数据点的一批。 以下是我们培训数据集中前十项项目的预测。

model.predict(train_images[0:10])

会给出模型推测的值。同样

model.predict(train_images[0:10]).argmax(1)

array([9, 0, 0, 6, 4, 4, 7, 4, 5, 5])

取一个图片的预测值,将预测的结果以条形图展示,对于

data_idx = 8675 # The question number to study with. Feel free to change up to 59999.

plt.figure()
plt.imshow(train_images[data_idx], cmap='gray')
plt.colorbar()
plt.grid(False)
plt.show()
#类别的标签
x_values = range(number_of_classes)
plt.figure()
#预测值
plt.bar(x_values, model.predict(train_images[data_idx:data_idx+1]).flatten())
plt.xticks(range(10))
plt.show()

print("correct answer:", train_labels[data_idx])

可以直接取值最大的那个查看是否预测正确。
在这里插入图片描述

3图像分割

主页链接
有segmentation
介绍tensorflow的一个接口
KERAS
Sequential和function
在这里插入图片描述
图片使用这个来显示

tf.keras.utils.plot_model(model, show_shapes=True)

工作流
在这里插入图片描述
登录配置好的远程环境,来进行实验,需要多等待一会。有两个小时的使用时间。
在这里插入图片描述

jupyter使用的介绍

在这里插入图片描述
下面先从使用notebook开始,notebook已经使用过很多次,但是只会一些基础的技巧,查看一下有没有一些好用的调试技巧。
首先是执行,可以使用(shift+enter)或者(ctrl+enter)来执行一个单元块。

每个块都有前缀,有导航,处理内核,标签等许多快捷打开,可以在不使用的时候缩回。
在这里插入图片描述
运行命令行命令时,可以直接使用!前缀,
在这里插入图片描述
nvidia-smi, which will print information about your environment’s available GPUs, their current memory usage, and any processes currently utilizing them:
可以查看到当前机器环境下的GPU和cuda环境。

魔法命令

常用的命令
拥有这些前缀的 % or %%。

%time and %%time which will print summary information about how long it took to run code for a line >or entire cell respectively.

打印代码运行时间

%load which will load the contents of a given file into the cell. We will be using this magic primarily to l?oad example solutions for after you complete exercises.

将给定内容加载到单元格里面
Magic Commands %time and %%time

from time import sleep

%time sleep(2) # %time only times one line
sleep(1)

CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 2 s

%%time
# %%time will time the entire cell

sleep(1)
sleep(1)

CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 2 s

Magic Command %load

% load 文件名

导入过大会卡死。
在这里插入图片描述

Managing Kernels in This Workshop

每个笔记本都有一个单独的内核。

  1. 您正在工作的笔记本除外,可能仍有为其独特的内核分配的记忆
  2. 从内核菜单重新启动内核只会清除当前笔记本内核的内存
    这是重启内核的命令
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)

记得多关闭内核,减小内存的占用。

进行图像分割的内容

医学图像的分割,超越图片的单个对象,组织分离。spatial regions of interest空间ROI。

目标

  • Understand how Neural Networks can solve imaging problems
  • Use Transpose Convolutional Neural Networks
  • Use Keras and TensorFlow 2 to analyze image data

Image Segmentation

下面会进行一些练习,可以叫做语义分割(semantic segmentation),对像素分类,从某种意义上说,这是一个分类问题,您将以像素为基础而不是整个图像进行分类。在本实验室中,任务将根据是否是左心室(LV)的一部分,将每个像素分类为心脏MRI图像。
该实验室不是对深度学习的介绍,也不是旨在成为卷积神经网络的严格数学形式主义。我们假设您至少对神经网络有一个传递的理解,包括诸如前进和反向传播,激活,SGD,卷积,汇总,偏见等概念。如果您已经遇到了卷积神经网络(CNN),并且您了解图像识别任务,这是有帮助的。该实验室将使用Google的Tensorflow机器学习框架,因此,如果您拥有Python和Tensorflow经验,则有用,但不需要。我们将在本实验室中所做的大多数工作不是编码本身,而是使用TensorFlow设置并运行培训和评估任务。

输入数据集

您将要使用的数据集是一系列已被标记的心脏图像(特别是MRI短轴(SAX)扫描)。有关完整的引文信息,请参见参考文献[1、2、3]。 数据的四个代表性示例如下所示。每行图像都是数据的一个实例。左侧是MRI图像,右侧是专门分段的区域(通常称为轮廓)。 LV一部分的图像部分用白色表示。请注意,LV的大小因图像而异,但LV通常占用整个图像的相对较小的区域。
在这里插入图片描述
从原始图像中提取数据,然后将这些图像的随后制备以摄入张量为tensorflow,将不会在本实验室中展示。可以说数据准备是机器学习工作流程的一个非平凡的方面,并且不在本实验室的范围之内。
对于那些对细节感兴趣的人,我们从先前的Kaggle竞争中获得了有关如何正确提取图像的指导和部分代码。那时,我们拍摄了图像,将它们转换为TensorFlow记录(TFRECORDS),然后将它们存储到文件中。 TfreCords是TensorFlow提供的一种特殊文件格式,它允许您使用内置的TensorFlow功能来进行数据管理,包括多线程数据阅读和对数据的复杂预处理,例如随机化甚至增强培训数据。
这些图像本身最初是256 x 256灰度DICOM格式,这是医学成像中的常见图像格式。标签是大小256 x 256 x2的张量。最后一个维度的原因是2是在两个类中的像素,因此每个像素标签具有与之相关的尺寸2的向量。训练集为234张图像,验证集(未用于训练的数据,而用于测试模型的准确性)为26张图像。

Tensorflow

tensorflow的介绍和手册(官方网址)https://www.tensorflow.org/

tensorflow的基础

Tensorflow 2已引入了Tensorflow 1.x的许多重要更新。对所有这些更改的讨论都超出了该实验室的范围,但是尤其是一个主要更改是Tensorflow 2的默认行为是在所谓的急切模式下执行。在Tensorflow 1.X中,必须构建一个模型,该模型本质上是数据流图。完成此完成后,您可以启动会话以通过模型运行培训数据。 Tensorflow 2.0更新此范式以在急切的模式下执行,这意味着命令按照其称为“典型的Python程序”执行。
该实验室将说明使用TF.KERAS库的使用,这是TensorFlow的Keras API规范的实现。 KERAS是一个高级神经网络API,根据Keras网站,“开发了侧重于实现快速实验”。在Keras中创建和训练网络很容易,因为它具有许多常见的神经网络层类型,例如,完全连接的层,卷积,丢弃(剪枝层)随机失效,池化或者聚集层和RNN。
Keras提供了一种简单的机制,可以将层连接在一起。有一个顺序(Sequential)模型,顾名思义,该模型允许一个人从一系列层构建一个神经网络,一个接一个地。如果您的神经网络结构更为复杂,则可以利用功能(Functional)API,该功能API允许由于非线性拓扑,共享层和具有多个输入的层而引起的自定义化。您甚至可以扩展功能API以创建自己的自定义层。这些不同的层类型可以混合并匹配,以构建您喜欢的任何类型的网络体系结构。 Keras为典型用例提供了许多出色的内置层类型,并允许用户在您的需求下构建复杂的层和模型。这些层由张量下面的张力支持,因此用户可以通过模型对自己关注,并让Tensorflow担心性能。

工作流

在这里插入图片描述

TensorBoard

TensorFlow提供了一个称为Tensorboard的功能富含功能的工具,该工具使您可以可视化程序的许多方面。在Tensorboard中,您可以看到计算图的视觉表示形式,并且可以绘制计算的不同指标,例如损失,准确性和学习率。从本质上讲,在执行TensorFlow期间生成的任何数据都可以通过张板视觉显示,并在程序中添加一些额外的API调用。 张板通过训练回调进入Keras

进入流程1准备数据

import datetime
import os

import tensorflow as tf
#导入后端
from tensorflow.keras import backend as K
#导入一些基本层的功能
from tensorflow.keras.layers import (
    Flatten, Dense, Reshape, Conv2D, MaxPool2D, Conv2DTranspose)
# 绘图的函数
import matplotlib.pyplot as plt

plt.rcParams['image.cmap'] = 'Greys_r'

rc的参数的说明
说明2

建立tensorflow的数据集

Next, we’ll load in our datasets. Since they’re already in a TFRecord format, we can supply their path to tf.data.TFRecordDataset. This will load the records into a tf.dataset, which is TensorFlow’s data pipeline tool, designed to ingest large amounts of data locally or from the cloud.
接下来,我们将加载数据集。由于它们已经采用tfrecord格式,因此我们可以向tf.data.tfrecorddataset提供其路径。这将将记录加载到TF.Dataset,即TensorFlow的数据管道工具,旨在在本地或从云中摄取大量数据。

数据如下:
在这里插入图片描述

# loading the training and test sets from TFRecords
raw_training_dataset = tf.data.TFRecordDataset('data/train_images.tfrecords')
raw_val_dataset      = tf.data.TFRecordDataset('data/val_images.tfrecords')

为了解析数据,我们需要提供其模式(schema)。对于每个功能,我们将定义其类和数据类型。由于每个图像的数据尺寸相同,因此我们将使用tf.io.fixedlenfeature类。

# dictionary describing the fields stored in TFRecord, and used to extract the date from the TFRecords
image_feature_description = {
    'height':    tf.io.FixedLenFeature([], tf.int64),
    'width':     tf.io.FixedLenFeature([], tf.int64),
    'depth':     tf.io.FixedLenFeature([], tf.int64),
    'name' :     tf.io.FixedLenFeature([], tf.string),
    'image_raw': tf.io.FixedLenFeature([], tf.string),
    'label_raw': tf.io.FixedLenFeature([], tf.string),
}

就是定义一下数据类型。
在这里插入图片描述
image_feature_description可用于用tf.io.parse_single_example解析每个tfrecord。由于记录已经在tf.dataset中,因此我们可以将解析映射到每个记录。
在这里插入图片描述

# helper function to extract an image from the dictionary
def _parse_image_function(example_proto):
	#传入原始数据,和图像描述的参数
    return tf.io.parse_single_example(example_proto, image_feature_description)
#训练集和测试集都进行解析。
parsed_training_dataset = raw_training_dataset.map(_parse_image_function)
parsed_val_dataset      = raw_val_dataset.map(_parse_image_function)

验证解析的数据

print(len(list(parsed_training_dataset)))
print(len(list(parsed_val_dataset)))

234
26

目前,我们的图像在字节中,并不类似于图像。让我们解决这个问题!我们将使用read_and_decode来使用tf.io.decode_raw将字节转换为整数向量。这仍然不是一个图像,因此使用TF.Reshape将其用于正方形的256x256x1阵列,每个单元格代表一个灰度像素。
神经网络接受浮点胜过整数类型,因此我们将图像缩小到0到1范围。我们不会使用标签图像来做到这一点,因为我们将使用那里的整数来表示我们的预测类。

# function to read and decode an example from the parsed dataset
@tf.function
def read_and_decode(example):
	#读入字节
    image_raw = tf.io.decode_raw(example['image_raw'], tf.int64)
    #像素是65536
    image_raw.set_shape([65536])
    image = tf.reshape(image_raw, [256, 256, 1])
	#映射,对于1/1024是对数据进行进一步的缩放。
    image = tf.cast(image, tf.float32) * (1. / 1024)
	#标签也进行解码,因为这里的标签也是图像,更确切的说是掩码蒙版。
    label_raw = tf.io.decode_raw(example['label_raw'], tf.uint8)
    label_raw.set_shape([65536])
    label = tf.reshape(label_raw, [256, 256, 1])
    #因为本身的数据类型足够小,可以不进行转换

    return image, label

我们可以像以前使用解析功能一样将此解码功能映射到数据集中的每个图像。

# get datasets read and decoded, and into a state usable by TensorFlow
#数据的自动调整。
tf_autotune = tf.data.experimental.AUTOTUNE
#将解析过的训练数据集映射到函数read_and_decode的结果
train = parsed_training_dataset.map(
    read_and_decode, num_parallel_calls=tf_autotune)
val = parsed_val_dataset.map(read_and_decode)
#查看元素特征
train.element_spec

(TensorSpec(shape=(256, 256, 1), dtype=tf.float32, name=None),
TensorSpec(shape=(256, 256, 1), dtype=tf.uint8, name=None))

数据的随机打乱
A few final things to consider with our dataset. Tf.datasets have a shuffle method to take X elements from our dataset and shuffle their order before passing them to the model. This is useful for large datasets that would be impossible to shiffle locally on a machine and critical for multi-worker training to keep the datasets different for each worker.
我们的数据集需要考虑最后一些事情。 tf.dataset具有一种重排的方法,可以从我们的数据集中获取X元素,并在将其传递给模型之前将其打乱。这对于大型数据集很有用,这些数据集将不可能在机器上本地进行打乱,并且对于多次并行调用至关重要,以使每个工人的数据集都不同。 另一方面,批次从缓冲区中获取Y元素,并将其分发给工人进行培训。
洗牌后抽取多少张再发出y。即使批次batch.

还有一种缓存(cache)方法可以将处理后的数据集存储在内存中,以加快训练时间和预取方法,该方法在当前批次用于培训时准备下一批数据。典型的管道在GPU上执行模型数据时会在CPU上准备数据。有关如何优化数据模型的更多信息,请参见此处的本文
出于此演示的目的,我们将使用10个缓冲区大小为10,批量大小为1。

# setup the buffer size and batch size for data reading and training
BUFFER_SIZE = 10
BATCH_SIZE = 1
# setup the train and test data by shuffling, prefetching, etc
train_dataset = train.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()
train_dataset = train_dataset.prefetch(buffer_size=tf_autotune)
test_dataset  = val.batch(BATCH_SIZE)
train_dataset

可视化数据集

由于我们正在使用图像,因此如果我们可以将输入图像与预测和真实标签进行比较,那将是很棒的。尽管AI的眼睛已经变得强大,但人眼仍然有助于检测数据中的异常并识别AI预测中的弱点。让我们创建一个函数,显示,比较我们的图像集。

# helper function to display an image, it's label and the prediction
def display(display_list):
	#图片的容量10*10。
    plt.figure(figsize=(10, 10))
    title = ['Input Image', 'Label', 'Predicted Label']

    for i in range(len(display_list)):
        #展示的缩放
        display_resized = tf.reshape(display_list[i], [256, 256])
        plt.subplot(1, len(display_list), i+1)
        plt.title(title[i])
        plt.imshow(display_resized)
        plt.axis('off')
    plt.show()

Bringing it all together, let’s take two batches from our dataset and visualize our input images and segmentation labels.

# display an image and label from the training set
for image, label in train.take(2):
    sample_image, sample_label = image, label
    display([sample_image, sample_label])

在这里插入图片描述
再次运行会获得两个新的图片。
接下来进入到TASK

TASK1

一个隐藏层的网络。
在这里插入图片描述

建立Keras 模型

我们首先要创建,训练和评估一个全链接的单层神经网络

  1. 神经网络的输入将是每个像素的值,即256 x 256 x 1(或65,536)阵列。 X 1是颜色通道的数量。由于图像是黑色和白色的,我们只使用1,但是如果它是颜色,我们可能会在RGB中使用X 3作为红色,绿色和蓝色。以下密集层期望矢量,而不是矩阵,因此我们将使传入的图像更扁平。
  2. 隐藏的密度层将具有一个可以调整到任何正整数的尺寸。
  3. 输出将具有256 x 256 x 2值,即,每个输入像素可以在两个类之一中,因此与每个像素关联的输出值将是像素在该特定类中的概率。在我们的情况下,这两个类是LV左心室。然后,我们将其重塑为256 x 256 x 2矩阵,以便将结果视为图像。

我们将通过称为Sparse_SoftMax_Cross_entropy_with_logits的TensorFlow函数来计算丢失,该功能只需将SoftMax与交叉熵计算结合到一个函数调用中。

tf.keras.backend.clear_session()

# set up the model architecture
model = tf.keras.models.Sequential([
	#定义输入层
    Flatten(input_shape=[256, 256, 1]),
    #一个中间层,使用relu的激活函数
    Dense(64, activation='relu'),
    Dense(256*256*2, activation='softmax'),
    Reshape((256, 256, 2))
])

# specify how to train the model with algorithm, the loss function and metrics
model.compile(
    optimizer='adam',
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'])

65536*(64+1)
64*(2562562+1)
在这里插入图片描述

# plot the model including the sizes of the model
tf.keras.utils.plot_model(model, show_shapes=True)

绘制结构图
在这里插入图片描述
在进行培训之前,让我们构建一些功能以可视化模型的学习方式。首先,我们将创建一个函数create_mask,该函数将取得我们的有效结果之一,并将其​​返回为256 x 256 x 1数组。每个单元格为1,意味着LV像素,而0,意味着没有LV。

我们将使用tf.argmax函数并观察最后一个维度轴= -1来做到这一点。我们有效地具有2个通道的图像,其概率在0个通道上的NO-LV概率和第1个通道上的概率LV。然后,tf.argmax将以较高的概率返回通道的索引,从而导致1 x 256 x 256数组。

n为将其绘制工具期望的256 x 256 x 1的形状放入256 x 256 x 1的形状中,我们将在末端附加一个新轴,然后选择第一个也是唯一的元素。

# function to take a prediction from the model and output an image for display
def create_mask(pred_mask):
	#预测的蒙版, #-1的含义是将图像展开,减少最后那个维度,前面比后面大为0,后面比前面大为1
    pred_mask = tf.argmax(pred_mask, axis=-1)
    #增加一个维度,从[1,255,255]到[1,255,255,1]
    pred_mask = pred_mask[..., tf.newaxis]
    return pred_mask[0]
# helper function to show the image, the label and the prediction
def show_predictions(dataset=None, num=1):
    if dataset:
        for image, label in dataset.take(num):
            pred_mask = model.predict(image)
            #print(pred_mask.shape)
            #print(pred_mask[0][0][0])
            #pred_test_mask = tf.argmax(pred_mask, axis=-1)
            #print(pred_test_mask.shape)
            #print(pred_test_mask[0][0])
            display([image[0], label[0], create_mask(pred_mask)])
    else:
        prediction = create_mask(model.predict(sample_image[tf.newaxis, ...]))
        display([sample_image, sample_label, prediction])

在这里插入图片描述

# show a predection, as an example
show_predictions(test_dataset)

在这里插入图片描述
接下来,我们将创建自己的自定义KERAS回调,以便在每个时期结束时,我们将看到模型对Sample_image的预测。我们还将设置一个张板回调,以便我们可以绘制培训结果。

# define a callback that shows image predictions on the test set
class DisplayCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        show_predictions()
        print ('\nSample Prediction after epoch {}\n'.format(epoch+1))

# setup a tensorboard callback
logdir = os.path.join("logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值