x = tf.random.uniform((10,3,3,3))
w = tf.random.uniform((1,3,3,3))
tf.reduce_sum(tf.multiply(x,w),axis=(1,2,3))
help(tf.multiply)
x = tf.random.uniform((10,28,28,3))
w = tf.random.uniform((6,3,3,3))
b = tf.random.uniform((6,))
x = tf.dtypes.cast(x,tf.float32)
N, H, W, C = tf.shape(x)
F, HH, WW,C = tf.shape(w)
Hn =1+int((H +2*0- HH)/1)
Wn =1+int((W +2*0- WW)/1)
Y = tf.Variable(tf.zeros((N, Hn, Wn, F)))for n inrange(N):for m inrange(F):for i inrange(Hn):for j inrange(Wn):
data = x[n, i *1:i *1+ HH, j *1:j *1+ WW,:]print(data.shape)
filt = w[n]print(tf.matmul(data,filt).shape)
Y[n, i, j, m].assign(tf.cast(tf.matmul(data,filt),dtype=tf.float32))
a = Conv2D()
tf
corr2d(x,w,b)
X = tf.constant([[0,1,2],[3,4,5],[6,7,8]])
K = tf.constant([[0,1],[2,3]])
a(X)
池化层
import tensorflow as tf
import numpy as np
defmax_pool_forward_naive(x, pool_size=(2,2),strides=(1,1)):
N, H, W, C = x.shape
h_p, w_p = pool_size
h_s, w_s = strides
Hn =1+int((H - h_p)/ h_s)
Wn =1+int((W - w_p)/ w_s)
out = np.zeros((N, Hn, Wn, C))for i inrange(Hn):for j inrange(Wn):
out[:, i, j,:]= np.max(x[:, i*h_s:i*h_s+h_p, j*w_s:j*w_s+w_p,:], axis=(1,2))return out
defpool2d(X, pool_size=(2,2),strides=(1,1)):
N, H, W, C = tf.shape(X)
p_h, p_w = pool_size
s_h, s_w = strides
Y = tf.zeros((N,(H - p_h +1)//s_h,(W - p_w +1)//s_w, C))
Y = tf.Variable(Y)for i in tf.range(tf.shape(Y)[1]):for j in tf.range(tf.shape(Y)[2]):
Y[:,i,j,:].assign(tf.math.reduce_max(X[:,i*s_h:i*s_h+p_h, j*s_w:j*s_w+p_w,:],axis=(1,2),keepdims=False))return Y