1. 程式人生 > 其它 >卷積運算-卷積類

卷積運算-卷積類

技術標籤:TensorFlow-深度學習卷積pythontensorflow深度學習卷積神經網路

# softmax 將實數值轉換為概率值
# 使用Keras介面如何操作
# import 匯入模組,每次使用模組中的函式都要是定是哪個模組。
# from…import * 匯入模組,每次使用模組中的函式,直接使用函式就可以了;
# 注因為已經知道該函式是那個模組中的了。
import tensorflow as tf
from tensorflow import keras 
from tensorflow.keras import layers ,Sequential
tf.__version__

卷積計算

# 輸入x
# [batch, in_height, in_width, in_channels]

x = tf.random.normal([1,5,5,3])
# 卷積核
# [filter_height * filter_width * in_channels, output_channels]
# 卷積核通道數要與輸入的通道數一致
# output_channels如果是1代表單卷積核,如果是其他數字代表多卷積核
w = tf.random.normal([3,3,3,6])
# 進行卷積操作
# strides 步長

out1 = tf.nn.conv2d(input
=x, filters=w, strides=[1,1,1,1], padding='SAME') # SAME 在step=1的時候,會得出輸出與輸入相同大小對映 # SAME step不等於1之後會按照公式進行補零(就是計算二維卷積結果的公式)會在四周補零 # VALID 不夠的不在補零計算,直接捨棄

卷積層類

conlayer = tf.keras.layers.Conv2D(filters=4,kernel_size=3)
out = conlayer(x)
out
<tf.Tensor: shape=(1, 3, 3, 4), dtype=float32, numpy=
array([[[[-1.3084283 ,  0.00293811, -0.40862942, -1.3523704 ],
         [-0.4729146 , -1.1206334 , -0.8556642 ,  0.7546072 ],
         [-1.1105286 ,  1.0177767 ,  1.090941  ,  0.48883992]],

        [[ 0.14009048, -0.6030586 ,  0.43579537, -0.4141754 ],
         [-0.69460857, -0.29528624,  0.79297507,  0.7033405 ],
         [ 1.6469915 , -1.1943179 , -0.23926653, -1.0635588 ]],

        [[ 0.02402557,  0.02041618,  0.9638242 ,  0.7419701 ],
         [ 0.17205958,  0.3290681 ,  0.44122928,  0.74784964],
         [-0.31854013,  0.3891179 ,  0.43354595, -0.16794361]]]],
      dtype=float32)>