目录
Convolutional Networks
1、卷积层
1.1简介
关于卷积神经网络的简介,架构等,我的另一篇博文介绍比较详细,这里就不再多说了。另外cs231n官网介绍入口在这里
直接上代码实现相关的图。
1.2、代码实现
前向传播
def conv_forward_naive(x, w, b, conv_param):
"""
A naive implementation of the forward pass for a convolutional layer.
The input consists of N data points, each with C channels, height H and
width W. We convolve each input with F different filters, where each filter
spans all C channels and has height HH and width WW.
Input:
- x: Input data of shape (N, C, H, W)
- w: Filter weights of shape (F, C, HH, WW)
- b: Biases, of shape (F,)
- conv_param: A dictionary with the following keys:
- 'stride': The number of pixels between adjacent receptive fields in the
horizontal and vertical directions.
- 'pad': The number of pixels that will be used to zero-pad the input.
During padding, 'pad' zeros should be placed symmetrically (i.e equally on both sides)
along the height and width axes of the input. Be careful not to modfiy the original
input x directly.
Returns a tuple of:
- out: Output data, of shape (N, F, H', W') where H' and W' are given by
H' = 1 + (H + 2 * pad - HH) / stride
W' = 1 + (W + 2 * pad - WW) / stride
- cache: (x, w, b, conv_param)
"""
out = None
###########################################################################
# TODO: Implement the convolutional forward pass. #
# Hint: you can use the function np.pad for padding. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
N, C, H, W = x.shape
F, C, HH, WW = w.shape
pad, stride = conv_param['pad'], conv_param['stride']
H_out = int(1 + (H + 2 * pad - HH) / stride)
W_out = int(1 + (W + 2 * pad - WW) / stride)
out = np.zeros([N, F, H_out, W_out])
x_pad = np.pad(x,((0,0),(0,0),(pad,pad),(pad,pad)))
for i in range(W_out):
for j in range(H_out):
for k in range(F):
for n in range(N):
out[n,k,j,i] = np.sum(x_pad[n,:,stride*j:HH+stride*j,stride*i:WW+stride*i] * w[k,:,:,:]) + b[k]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = (x, w, b, conv_param)
return out, cache
反向传播
def conv_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b
"""
dx, dw, db = None, None, None
###########################################################################
# TODO: Implement the convolutional backward pass. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
x, w, b, conv_param = cache
N, C, H, W = x.shape
F, C, HH, WW = w.shape
H_out = dout.shape[2]
W_out = dout.shape[3]
pad, stride = conv_param['pad'], conv_param['stride']
x_pad = np.pad(x,((0,0),(0,0),(pad,pad),(pad,pad)))
dx_pad = np.zeros([N,C,H+2*pad,W+2*pad])
dw = np.zeros(w.shape)
db = np.zeros(b.shape)
for i in range(W_out):
for j in range(H_out):
for k in range(F):
for n in range(N):
dx_pad[n,:,stride*j:HH+stride*j,stride*i:WW+stride*i] += dout[n,k,j,i] * w[k,:,:,:]
dw[k,:,:,:] += dout[n,k,j,i] * x_pad[n,:,stride*j:HH+stride*j,stride*i:WW+stride*i]
db[k] += dout[n,k,j,i]
dx = dx_pad[:,:,pad:H+pad,pad:W+pad]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dw, db
2、池化层
2.1、代码实现
前向传播
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max-pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
No padding is necessary here. Output size is given by
Returns a tuple of:
- out: Output data, of shape (N, C, H', W') where H' and W' are given by
H' = 1 + (H - pool_height) / stride
W' = 1 + (W - pool_width) / stride
- cache: (x, pool_param)
"""
out = None
###########################################################################
# TODO: Implement the max-pooling forward pass #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
N, C, H, W = x.shape
pool_height = pool_param['pool_height']
pool_width = pool_param['pool_width']
stride = pool_param['stride']
H_out = int(1 + (H - pool_height) / stride)
W_out = int(1 + (W - pool_width) / stride)
out = np.zeros([N, C, H_out, W_out])
for i in range(W_out):
for j in range(H_out):
out[:,:,j,i] = np.max(x[:,:,j*stride:pool_height+j*stride,i*stride:pool_width+i*stride],axis=(2,3))
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
cache = (x, pool_param)
return out, cache
反向传播
def max_pool_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a max-pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
dx = None
###########################################################################
# TODO: Implement the max-pooling backward pass #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
x, pool_param = cache
stride = pool_param['stride']
pool_height = pool_param['pool_height']
pool_width = pool_param['pool_width']
dx = np.zeros(x.shape)
N, C, H_out, W_out = dout.shape
for i in range(W_out):
for j in range(H_out):
mask = np.max(x[:,:,j*stride:pool_height+j*stride,i*stride:pool_width+i*stride],\
axis=(2,3),keepdims=True)
flag = (mask == x[:,:,j*stride:pool_height+j*stride,i*stride:pool_width+i*stride])
dx[:,:,j*stride:pool_height+j*stride,i*stride:pool_width+i*stride] = flag * (dout[:,:,j,i])[:,:,None,None]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx
3、实现三层卷积网络
3.1、代码实现
class ThreeLayerConvNet(object):
"""
A three-layer convolutional network with the following architecture:
conv - relu - 2x2 max pool - affine - relu - affine - softmax
The network operates on minibatches of data that have shape (N, C, H, W)
consisting of N images, each with height H and width W and with C input
channels.
"""
def __init__(
self,
input_dim=(3, 32, 32),
num_filters=32,
filter_size=7,
hidden_dim=100,
num_classes=10,
weight_scale=1e-3,
reg=0.0,
dtype=np.float32,
):
"""
Initialize a new network.
Inputs:
- input_dim: Tuple (C, H, W) giving size of input data
- num_filters: Number of filters to use in the convolutional layer
- filter_size: Width/height of filters to use in the convolutional layer
- hidden_dim: Number of units to use in the fully-connected hidden layer
- num_classes: Number of scores to produce from the final affine layer.
- weight_scale: Scalar giving standard deviation for random initialization
of weights.
- reg: Scalar giving L2 regularization strength
- dtype: numpy datatype to use for computation.
"""
self.params = {}
self.reg = reg
self.dtype = dtype
############################################################################
# TODO: Initialize weights and biases for the three-layer convolutional #
# network. Weights should be initialized from a Gaussian centered at 0.0 #
# with standard deviation equal to weight_scale; biases should be #
# initialized to zero. All weights and biases should be stored in the #
# dictionary self.params. Store weights and biases for the convolutional #
# layer using the keys 'W1' and 'b1'; use keys 'W2' and 'b2' for the #
# weights and biases of the hidden affine layer, and keys 'W3' and 'b3' #
# for the weights and biases of the output affine layer. #
# #
# IMPORTANT: For this assignment, you can assume that the padding #
# and stride of the first convolutional layer are chosen so that #
# **the width and height of the input are preserved**. Take a look at #
# the start of the loss() function to see how that happens. #
############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
F = num_filters
HH = filter_size
WW = filter_size
C, H, W = input_dim
self.params['W1'] = np.random.randn(F,C,HH,WW) * weight_scale
self.params['b1'] = np.zeros(F)
self.params['W2'] = np.random.randn(int(F*H*W/4),hidden_dim) * weight_scale
self.params['b2'] = np.zeros(hidden_dim)
self.params['W3'] = np.random.randn(hidden_dim, num_classes) * weight_scale
self.params['b3'] = np.zeros(num_classes)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
############################################################################
# END OF YOUR CODE #
############################################################################
for k, v in self.params.items():
self.params[k] = v.astype(dtype)
def loss(self, X, y=None):
"""
Evaluate loss and gradient for the three-layer convolutional network.
Input / output: Same API as TwoLayerNet in fc_net.py.
"""
W1, b1 = self.params["W1"], self.params["b1"]
W2, b2 = self.params["W2"], self.params["b2"]
W3, b3 = self.params["W3"], self.params["b3"]
# pass conv_param to the forward pass for the convolutional layer
# Padding and stride chosen to preserve the input spatial size
filter_size = W1.shape[2]
conv_param = {"stride": 1, "pad": (filter_size - 1) // 2}
# pass pool_param to the forward pass for the max-pooling layer
pool_param = {"pool_height": 2, "pool_width": 2, "stride": 2}
scores = None
############################################################################
# TODO: Implement the forward pass for the three-layer convolutional net, #
# computing the class scores for X and storing them in the scores #
# variable. #
# #
# Remember you can use the functions defined in cs231n/fast_layers.py and #
# cs231n/layer_utils.py in your implementation (already imported). #
############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#conv - relu - 2x2 max pool - affine - relu - affine - softmax
conv_out, cache_conv = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param)
hidden, cache_hidden = affine_relu_forward(conv_out, W2, b2)
scores, cache_score = affine_forward(hidden, W3, b3)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
############################################################################
# END OF YOUR CODE #
############################################################################
if y is None:
return scores
loss, grads = 0, {}
############################################################################
# TODO: Implement the backward pass for the three-layer convolutional net, #
# storing the loss and gradients in the loss and grads variables. Compute #
# data loss using softmax, and make sure that grads[k] holds the gradients #
# for self.params[k]. Don't forget to add L2 regularization! #
# #
# NOTE: To ensure that your implementation matches ours and you pass the #
# automated tests, make sure that your L2 regularization includes a factor #
# of 0.5 to simplify the expression for the gradient. #
############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
#forward
conv_out, cache_conv = conv_relu_pool_forward(X, W1, b1, conv_param, pool_param)
hidden, cache_hidden = affine_relu_forward(conv_out, W2, b2)
scores, cache_score = affine_forward(hidden, W3, b3)
loss, dscore = softmax_loss(scores, y)
loss += self.reg * 0.5 * (np.sum(W1*W1) + np.sum(W2*W2) + np.sum(W3*W3))
#backward
dhidden, dW3, db3 = affine_backward(dscore, cache_score)
grads['W3'] = dW3 + self.reg * W3
grads['b3'] = db3
dconv_out, dW2, db2 = affine_relu_backward(dhidden, cache_hidden)
grads['W2'] = dW2 + self.reg * W2
grads['b2'] = db2
dX, dW1, db1 = conv_relu_pool_backward(dconv_out, cache_conv)
grads['W1'] = dW1 + self.reg * W1
grads['b1'] = db1
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
############################################################################
# END OF YOUR CODE #
############################################################################
return loss, grads
4、Spatial Batch Normalization
4.1、简介
一般的Batch Normalization的输入维度是(N, D),对N个输入样本进行归一化操作,输出维度是(N, D)
Spatial Batch Normalization的输入维度是(N,C,H,W),对C个通道进行归一化操作,输出维度是(N,C,H,W)
N是样本数量,C是通道数(eg:RGB三通道),H是图片的高(像素点数),W是图片的宽(像素点数)
4.2代码实现
代码实现复用了之前Batch Normalization的函数
前向传播
def spatial_batchnorm_forward(x, gamma, beta, bn_param):
"""
Computes the forward pass for spatial batch normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (C,)
- beta: Shift parameter, of shape (C,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance. momentum=0 means that
old information is discarded completely at every time step, while
momentum=1 means that new information is never incorporated. The
default of momentum=0.9 should work well in most situations.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: Output data, of shape (N, C, H, W)
- cache: Values needed for the backward pass
"""
out, cache = None, None
###########################################################################
# TODO: Implement the forward pass for spatial batch normalization. #
# #
# HINT: You can implement spatial batch normalization by calling the #
# vanilla version of batch normalization you implemented above. #
# Your implementation should be very short; ours is less than five lines. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
N, C, H, W = x.shape
x_temp = x.transpose(0,2,3,1).reshape(N*H*W, C)
out, cache = batchnorm_forward(x_temp, gamma, beta, bn_param)
out = out.reshape(N,H,W,C).transpose(0,3,1,2)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return out, cache
反向传播
def spatial_batchnorm_backward(dout, cache):
"""
Computes the backward pass for spatial batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (C,)
- dbeta: Gradient with respect to shift parameter, of shape (C,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for spatial batch normalization. #
# #
# HINT: You can implement spatial batch normalization by calling the #
# vanilla version of batch normalization you implemented above. #
# Your implementation should be very short; ours is less than five lines. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
(N, C, H, W) = dout.shape
dout_temp = dout.transpose(0,2,3,1).reshape(N*H*W, C)
dx, dgamma, dbeta = batchnorm_backward_alt(dout_temp, cache)
dx = dx.reshape(N,H,W,C).transpose(0,3,1,2)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
5、Group Normalization
5.1、简介
Group Normalization是2018年提出来的方法,论文地址。
一张图展示Batch Norm, Layer Norm ,Group Norm的区别
N是样本数量,C是通道数(eg:RGB三通道),H是图片的高(像素点数),W是图片的宽(像素点数)
Group Norm可以理解为在layer Norm的基础上,输入维度为(N,C,H,W),对C进行分组,即为(N,G,C//G,H,W),对N个通道G个组进行归一化,输出维度为(N,G,C//G,H,W),再还原输出维度为(N,C,H,W)
5.2、代码实现
前向传播
def spatial_groupnorm_forward(x, gamma, beta, G, gn_param):
"""
Computes the forward pass for spatial group normalization.
In contrast to layer normalization, group normalization splits each entry
in the data into G contiguous pieces, which it then normalizes independently.
Per feature shifting and scaling are then applied to the data, in a manner identical to that of batch normalization and layer normalization.
Inputs:
- x: Input data of shape (N, C, H, W)
- gamma: Scale parameter, of shape (C,)
- beta: Shift parameter, of shape (C,)
- G: Integer mumber of groups to split into, should be a divisor of C
- gn_param: Dictionary with the following keys:
- eps: Constant for numeric stability
Returns a tuple of:
- out: Output data, of shape (N, C, H, W)
- cache: Values needed for the backward pass
"""
out, cache = None, None
eps = gn_param.get("eps", 1e-5)
###########################################################################
# TODO: Implement the forward pass for spatial group normalization. #
# This will be extremely similar to the layer norm implementation. #
# In particular, think about how you could transform the matrix so that #
# the bulk of the code is similar to both train-time batch normalization #
# and layer normalization! #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
(N, C, H, W) = x.shape
x_temp = x.reshape((N,G,C//G,H,W))
mean = np.mean(x_temp, axis=(2,3,4), keepdims=True)
var = np.var(x_temp, axis=(2,3,4), keepdims=True)
xhat = (x_temp - mean) / np.sqrt(var + eps)
xhat = xhat.reshape((N, C, H, W))
out = xhat * gamma + beta
cache = xhat, gamma, beta, x, var, mean, eps, G
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return out, cache
反向传播
def spatial_groupnorm_backward(dout, cache):
"""
Computes the backward pass for spatial group normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, C, H, W)
- cache: Values from the forward pass
Returns a tuple of:
- dx: Gradient with respect to inputs, of shape (N, C, H, W)
- dgamma: Gradient with respect to scale parameter, of shape (C,)
- dbeta: Gradient with respect to shift parameter, of shape (C,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for spatial group normalization. #
# This will be extremely similar to the layer norm implementation. #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
xhat, gamma, beta, x, var, mean, eps, G = cache
N,C,H,W = x.shape
k = H * W * C//G
dgamma = np.sum((dout * xhat),axis=(0,2,3),keepdims=True)
dbeta = np.sum(dout,axis=(0,2,3),keepdims=True)
print('dbeta',dbeta.shape)
dxhat = (dout * gamma).reshape(N,G,C//G,H,W)
x = x.reshape(N,G,C//G,H,W)
dvar = np.sum(dxhat * (x - mean) * (-0.5) * np.power(var+eps,-1.5),axis=(2,3,4),keepdims=True)
dmean = np.sum(-dxhat / np.sqrt(var+eps) + dvar * (-2/k) * (x - mean),axis=(2,3,4),keepdims=True)
dx = dxhat / np.sqrt(var+eps) + dvar * (2/k) * (x-mean) + dmean / k
dx = dx.reshape(N,C,H,W)
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta