TensorFlow2简单入门

TensorFlow2简单入门-四维张量

2021-01-17  本文已影响0人  K同学啊
TensorFlow2简单入门

四维张量在卷积神经网络(CNN)中广泛应用,一般用于保存特征图(Feature maps)数据,格式一般定义为

[𝑏, ℎ, w, 𝑐]

其中𝑏表示输入样本的数量; ℎ表示特征图的高;w表示特征图的宽; 𝑐表示特征图的通道数。

先来看一份代码

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# 将像素的值标准化至0到1的区间内。
train_images, test_images = train_images / 255.0, test_images / 255.0

train_images.shape,test_images.shape,train_labels.shape,test_labels.shape
'''
输出:
((50000, 32, 32, 3), (10000, 32, 32, 3), (50000, 1), (10000, 1))
'''

(50000, 32, 32, 3)中,50000是图片数目,图片是32×32的,3表示每个像素点都有3个值表示颜色(即彩色图像)。

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(20,10))
for i in range(20):
    plt.subplot(5,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    
    plt.xlabel(class_names[train_labels[i][0]])
plt.show()
彩色图像

对比灰度图像:

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()

# 将像素的值标准化至0到1的区间内。
train_images, test_images = train_images / 255.0, test_images / 255.0

train_images.shape,test_images.shape,train_labels.shape,test_labels.shape
"""
输出:
((60000, 28, 28), (10000, 28, 28), (60000,), (10000,))
"""

灰度图像仅用三维张量即可表示。

plt.figure(figsize=(20,10))
for i in range(20):
    plt.subplot(5,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)

    plt.xlabel(train_labels[i])
plt.show()
灰度图像
上一篇下一篇

猜你喜欢

热点阅读