1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
| import numpy as np
class Conv3x3: def __init__(self, num_filters, learn_rate=0.01): self.num_filters = num_filters self.filters = np.random.randn(num_filters, 3, 3) / 9
self.last_input = None self.learn_rate = learn_rate
def iterate_regions(self, image): h, w = image.shape for i in range(h - 2): for j in range(w - 2): im_region = image[i:(i + 3), j:(j + 3)] yield im_region, i, j
def forward(self, input): self.last_input = input h, w = input.shape output = np.zeros((h - 2, w - 2, self.num_filters)) for im_region, i, j in self.iterate_regions(input): output[i, j] = np.sum(im_region * self.filters, axis=(1, 2))
return output
def backprop(self, d_L_d_out): d_L_d_filters = np.zeros(self.filters.shape)
for im_region, i, j in self.iterate_regions(self.last_input): for f in range(self.num_filters): d_L_d_filters[f] += d_L_d_out[i, j, f] * im_region
self.filters -= self.learn_rate * d_L_d_filters
return None
class MaxPool2: def __init__(self): self.last_input = None
def iterate_regions(self, image): h, w, _ = image.shape new_h = h // 2 new_w = w // 2
for i in range(new_h): for j in range(new_w): im_region = image[i * 2:(i + 1) * 2, j * 2:(j + 1) * 2] yield im_region, i, j
def forward(self, input): self.last_input = input h, w, num_filters = input.shape output = np.zeros((h // 2, w // 2, num_filters))
for im_region, i, j in self.iterate_regions(input): output[i, j] = np.amax(im_region, axis=(0, 1))
return output
def backprop(self, d_L_d_out): d_L_d_input = np.zeros(self.last_input.shape) for im_region, i, j in self.iterate_regions(self.last_input): h, w, f = im_region.shape amax = np.amax(im_region, axis=(0, 1))
for i2 in range(h): for j2 in range(w): for f2 in range(f): if im_region[i2, j2, f2] == amax[f2]: d_L_d_input[i * 2 + i2, j * 2 + j2, f2] = d_L_d_out[i, j, f2] return d_L_d_input
class Softmax: def __init__(self, input_len, nodes, learn_rate=0.01): self.weights = np.random.randn(input_len, nodes) / nodes self.biases = np.zeros(nodes) self.learn_rate = learn_rate
self.last_input_shape = None self.last_input = None self.last_totals = None
def forward(self, input): self.last_input_shape = input.shape input = input.flatten() self.last_input = input
totals = np.dot(input, self.weights) + self.biases self.last_totals = totals exp = np.exp(totals)
return exp / np.sum(exp, axis=0)
def backprop(self, d_L_d_out): d_L_d_w = np.zeros(self.weights.shape) d_L_d_b = np.zeros(self.biases.shape) d_L_d_input = np.zeros(self.last_input.shape) for i, gradient in enumerate(d_L_d_out): if gradient == 0: continue t_exp = np.exp(self.last_totals) S = np.sum(t_exp) d_out_d_t = -t_exp[i] * t_exp / (S ** 2) d_out_d_t[i] = t_exp[i] * (S - t_exp[i]) / (S ** 2) d_t_d_w = self.last_input d_t_d_b = 1 d_t_d_input = self.weights d_L_d_t = gradient * d_out_d_t d_L_d_w += d_t_d_w[np.newaxis].T @ d_L_d_t[np.newaxis] d_L_d_b += d_L_d_t * d_t_d_b d_L_d_input += d_t_d_input @ d_L_d_t self.weights -= self.learn_rate * d_L_d_w self.biases -= self.learn_rate * d_L_d_b return d_L_d_input.reshape(self.last_input_shape)
import pickle
class ModelSaver: def __init__(self, model_name='MNIST_CNN'): self.model_name = model_name
def save(self, conv, pool, softmax): data = { 'conv_filters': conv.filters, 'softmax_weights': softmax.weights, 'softmax_biases': softmax.biases } filename = f'{self.model_name}.pkl' with open(filename, 'wb') as f: pickle.dump(data, f) print(f"保存参数到{filename}")
def load(self, conv, pool, softmax): filename = f'{self.model_name}.pkl' try: with open(filename, 'rb') as f: data = pickle.load(f)
conv.filters = data['conv_filters'] softmax.weights = data['softmax_weights'] softmax.biases = data['softmax_biases'] print("模型参数加载成功") return True
except FileNotFoundError: print("无可用模型参数") return False
import tkinter as tk from PIL import Image,ImageDraw,ImageOps
class DrawingBoard: def __init__(self, root): self.root = root self.root.title("画板")
self.canvas = tk.Canvas(root, width=280, height=280, bg='white') self.canvas.pack()
self.canvas.bind("<B1-Motion>", self.paint)
self.image = Image.new("RGB", (280, 280), "white") self.draw = ImageDraw.Draw(self.image)
self.brush_color = "black" self.brush_width = 5
self.output_button = tk.Button(root, text="输出", command=self.output_and_exit) self.output_button.pack()
def paint(self, event): x1, y1 = (event.x - self.brush_width), (event.y - self.brush_width) x2, y2 = (event.x + self.brush_width), (event.y + self.brush_width) self.canvas.create_oval(x1, y1, x2, y2, fill=self.brush_color, outline=self.brush_color) self.draw.ellipse([x1, y1, x2, y2], fill=self.brush_color, outline=self.brush_color)
def process_image(self): processed_image = self.image.resize((28, 28), Image.Resampling.LANCZOS) processed_image = ImageOps.grayscale(processed_image)
image_array = np.array(processed_image)
image_array = image_array.astype(np.uint8)
return image_array
def output_and_exit(self): self.image_array = self.process_image()
processed_image = Image.fromarray(self.image_array) processed_image.save("temp.png") print("图片已保存为 temp.png")
self.root.destroy()
|