
TensorFlow2簡(jiǎn)單入門(mén)
四維張量在卷積神經(jīng)網(wǎng)絡(luò)(CNN)中廣泛應(yīng)用,一般用于保存特征圖(Feature maps)數(shù)據(jù),格式一般定義為
其中??表示輸入樣本的數(shù)量; ?表示特征圖的高;w表示特征圖的寬; ??表示特征圖的通道數(shù)。
先來(lái)看一份代碼
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()
# 將像素的值標(biāo)準(zhǔn)化至0到1的區(qū)間內(nèi)。
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是圖片數(shù)目,圖片是32×32的,3表示每個(gè)像素點(diǎn)都有3個(gè)值表示顏色(即彩色圖像)。
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()

彩色圖像
對(duì)比灰度圖像:
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()
# 將像素的值標(biāo)準(zhǔn)化至0到1的區(qū)間內(nèi)。
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()

灰度圖像