MCPcopy
hub / github.com/ddbourgin/numpy-ml / test_Conv2D

Function test_Conv2D

numpy_ml/tests/test_nn.py:1130–1213  ·  view source on GitHub ↗
(N=15)

Source from the content-addressed store, hash-verified

1128
1129
1130def test_Conv2D(N=15):
1131 from numpy_ml.neural_nets.layers import Conv2D
1132 from numpy_ml.neural_nets.activations import Tanh, ReLU, Sigmoid, Affine
1133
1134 N = np.inf if N is None else N
1135
1136 np.random.seed(12345)
1137
1138 acts = [
1139 (Tanh(), nn.Tanh(), "Tanh"),
1140 (Sigmoid(), nn.Sigmoid(), "Sigmoid"),
1141 (ReLU(), nn.ReLU(), "ReLU"),
1142 (Affine(), TorchLinearActivation(), "Affine"),
1143 ]
1144
1145 i = 1
1146 while i < N + 1:
1147 n_ex = np.random.randint(1, 10)
1148 in_rows = np.random.randint(1, 10)
1149 in_cols = np.random.randint(1, 10)
1150 n_in, n_out = np.random.randint(1, 3), np.random.randint(1, 3)
1151 f_shape = (
1152 min(in_rows, np.random.randint(1, 5)),
1153 min(in_cols, np.random.randint(1, 5)),
1154 )
1155 p, s = np.random.randint(0, 5), np.random.randint(1, 3)
1156 d = np.random.randint(0, 5)
1157
1158 fr, fc = f_shape[0] * (d + 1) - d, f_shape[1] * (d + 1) - d
1159 out_rows = int(1 + (in_rows + 2 * p - fr) / s)
1160 out_cols = int(1 + (in_cols + 2 * p - fc) / s)
1161
1162 if out_rows <= 0 or out_cols <= 0:
1163 continue
1164
1165 X = random_tensor((n_ex, in_rows, in_cols, n_in), standardize=True)
1166
1167 # randomly select an activation function
1168 act_fn, torch_fn, act_fn_name = acts[np.random.randint(0, len(acts))]
1169
1170 # initialize Conv2D layer
1171 L1 = Conv2D(
1172 out_ch=n_out,
1173 kernel_shape=f_shape,
1174 act_fn=act_fn,
1175 pad=p,
1176 stride=s,
1177 dilation=d,
1178 )
1179
1180 # forward prop
1181 y_pred = L1.forward(X)
1182
1183 # backprop
1184 dLdy = np.ones_like(y_pred)
1185 dLdX = L1.backward(dLdy)
1186
1187 # get gold standard gradients

Callers

nothing calls this directly

Calls 12

forwardMethod · 0.95
backwardMethod · 0.95
extract_gradsMethod · 0.95
TanhClass · 0.90
SigmoidClass · 0.90
ReLUClass · 0.90
AffineClass · 0.90
random_tensorFunction · 0.90
Conv2DClass · 0.90
TorchConv2DLayerClass · 0.85
err_fmtFunction · 0.70

Tested by

no test coverage detected