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
| import random import time import numpy as np
class Network(object):
def __init__(self, sizes): self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y, 1) for y in sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]
def feedforward(self, a): for b, w in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a)+b) return a
def SGD(self, train_data, epochs, mini_batch_size, learning_rate): n = len(train_data) for j in range(epochs): if j % 50 == 0: start_time = time.time() random.shuffle(train_data) mini_batches = [train_data[k:k+mini_batch_size] for k in range(0, n, mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, learning_rate) if (j + 1) % 50 == 0: end_time = time.time() elapsed_time = end_time - start_time print("Epoch {0}-{1} complete in {2:.3f} seconds".format(j - 49, j, elapsed_time))
def update_mini_batch(self, mini_batch, learning_rate): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] self.weights = [w-(learning_rate/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(learning_rate/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)]
def backprop(self, x, y): """ 执行反向传播算法,计算损失函数关于权重和偏置的梯度。
参数: x (np.ndarray): 单个输入样本的特征向量。 y (np.ndarray): 该输入样本对应的目标输出向量。
返回: tuple: 包含偏置梯度和权重梯度的元组 (nabla_b, nabla_w)。 """ nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] activation = x activations = [x] zs = [] for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = sigmoid(z) activations.append(activation) delta = self.cost_derivative(activations[-1], y) * sigmoid_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) for l in range(2, self.num_layers): z = zs[-l] sp = sigmoid_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w)
def evaluate(self, test_data): test_results = [(np.argmax(self.feedforward(x)), np.argmax(y)) for (x, y) in test_data] correct_count = sum(int(x == y) for (x, y) in test_results) error_indices = [i for i, (x, y) in enumerate(test_results) if x != y] return correct_count, error_indices
def cost_derivative(self, output_activations, y): return (output_activations-y)
def sigmoid(z): return 1.0/(1.0+np.exp(-z))
def sigmoid_prime(z): return sigmoid(z)*(1-sigmoid(z))
def loadData(path): data = [] with open(path,'r') as file: for line in file: line = line.strip().split() features = np.array([float(x) for x in line[:-1]]).reshape(-1,1) label = np.zeros((3,1)) label[int(line[-1])] = 1 data.append((features,label)) return data
def normalization(data): normalized_data = [] for i in range(len(data)): ndata = (data[i][0] - np.min(data[i][0])) / (np.max(data[i][0]) - np.min(data[i][0])) normalized_data.append((ndata, data[i][1])) return normalized_data
traindata = loadData('Iris-train.txt') testdata = loadData('Iris-test.txt')
''' traindata = [ ( np.array([[5.1], [3.5], [1.4], [0.2]]), # 第一个样本的特征 np.array([[1], [0], [0]]) #第一个样本的标签(独热编码) ), #其他样本... ] traindata[0]:获取 traindata 列表中的第一个样本,它是一个包含特征和标签的元组。 traindata[0][0]:获取 traindata 列表中第一个样本的特征数据。 traindata[0][1]:获取 traindata 列表中第一个样本的标签数据。 '''
traindata = normalization(traindata) testdata = normalization(testdata)
trainacc = [] testacc = [] train_error_info = [] test_error_info = []
for iteration in range(10): model = Network([4, 10, 3])
model.SGD(traindata, epochs=750, mini_batch_size=10, learning_rate=0.12)
train_correct, train_error_indices = model.evaluate(traindata) trainacc.append(train_correct / len(traindata)) train_error_info.append((train_error_indices, train_correct, len(traindata)))
test_correct, test_error_indices = model.evaluate(testdata) testacc.append(test_correct / len(testdata)) test_error_info.append((test_error_indices, test_correct, len(testdata)))
print("训练集准确率") for i, acc in enumerate(trainacc): print(f"第 {i + 1} 次: {acc * 100:.2f}%") error_indices, correct, total = train_error_info[i] print(f"错误编号: {error_indices}") print(f"正确/总数: {correct}/{total}")
print("测试集准确率") for i, acc in enumerate(testacc): print(f"第 {i + 1} 次: {acc * 100:.2f}%") error_indices, correct, total = test_error_info[i] print(f"错误编号: {error_indices}") print(f"正确/总数: {correct}/{total}")
print(f"训练平均准确率: {np.mean(trainacc) * 100:.2f}%, 标准差: {np.std(trainacc):.3f}") print(f"测试平均准确率: {np.mean(testacc) * 100:.2f}%, 标准差: {np.std(testacc):.3f}")
|