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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
| import os import time import numpy as np import matplotlib.pyplot as plt import pickle from tqdm import tqdm from utils import load_and_augment_images,load_images,load_images_for_prediction from features import extract_hog, extract_lbp import matplotlib matplotlib.use('TkAgg') import pandas as pd
pca_components = 100 svm_lr = 0.01 svm_epochs = 100 svm_C = 0.1 batch_size = 32 momentum = 0.9
def standardize_train(X): mean = np.mean(X, axis=0) std = np.std(X, axis=0) + 1e-8 return (X - mean) / std, mean, std
def standardize_test(X, mean, std): return (X - mean) / std
def randomized_pca(X, n_components, n_iter=3): from numpy.random import randn X = X - np.mean(X, axis=0) m, n = X.shape Q = randn(n, n_components + 10) Y = X @ Q
for _ in range(n_iter): Y = X @ (X.T @ Y)
from numpy.linalg import qr Q, _ = qr(Y)
B = Q.T @ X U_hat, S, Vt = np.linalg.svd(B, full_matrices=False) components = Vt[:n_components].T
return components
class PCA: def __init__(self, n_components): self.n_components = n_components self.mean = None self.components = None
def fit(self, X): self.mean = np.mean(X, axis=0) X_centered = X - self.mean self.components = randomized_pca(X_centered, self.n_components)
def transform(self, X): return (X - self.mean) @ self.components
def fit_transform(self, X): self.fit(X) return self.transform(X)
class LinearSVM: def __init__(self, lr=0.01, epochs=100, C=1.0, momentum=0.9): self.lr = lr self.epochs = epochs self.C = C self.momentum = momentum self.w = None self.b = 0 self.loss_history = [] self.acc_history = []
def fit(self, X, y): n_samples, n_features = X.shape self.w = np.zeros(n_features) self.b = 0 y_ = np.where(y == 1, 1, -1)
v_w = np.zeros_like(self.w) v_b = 0
indices = np.arange(n_samples)
for epoch in tqdm(range(self.epochs), desc="Training SVM"): np.random.shuffle(indices) X, y_ = X[indices], y_[indices]
loss = 0 correct = 0
for i in range(0, n_samples, batch_size): X_batch = X[i:i + batch_size] y_batch = y_[i:i + batch_size]
margins = y_batch * (np.dot(X_batch, self.w) + self.b)
mask = margins < 1
dw = 2 * self.w - self.C * np.dot((y_batch[mask])[:, np.newaxis].T, X_batch[mask]).flatten() db = -self.C * np.sum(y_batch[mask])
v_w = self.momentum * v_w + self.lr * dw v_b = self.momentum * v_b + self.lr * db
self.w -= v_w self.b -= v_b
loss += np.mean(np.maximum(0, 1 - margins)) + self.C * np.sum(self.w ** 2) y_pred = np.sign(np.dot(X_batch, self.w) + self.b) correct += np.sum(y_pred == y_batch)
self.loss_history.append(loss / n_samples) self.acc_history.append(correct / n_samples)
def predict(self, X): return np.where(np.dot(X, self.w) + self.b >= 0, 1, 0)
def normalize(features): mean = np.mean(features, axis=0) std = np.std(features, axis=0) return (features - mean) / (std + 1e-8) ''' def extract_features(X): all_features = [] for img in tqdm(X, desc="Extracting features"): hog = extract_hog(img) lbp, _ = extract_lbp(img) # 只是堆叠了起来 combined = np.concatenate([hog, lbp]) all_features.append(combined) return np.array(all_features) '''
def extract_features(X): all_features = [] for img in tqdm(X, desc="Extracting features"): hog = extract_hog(img) lbp, _ = extract_lbp(img)
hog_norm = normalize(hog) lbp_norm = normalize(lbp)
combined = np.concatenate([hog_norm, lbp_norm]) all_features.append(combined) return np.array(all_features)
def plot_training_curve(loss, acc, save_path="svm_training_plot.png"): plt.figure(figsize=(10, 4)) plt.subplot(1, 2, 1) plt.plot(loss, label='Loss') plt.title("Hinge Loss") plt.xlabel("Epoch") plt.ylabel("Loss") plt.grid(True)
plt.subplot(1, 2, 2) plt.plot(acc, label='Accuracy', color='green') plt.title("Training Accuracy") plt.xlabel("Epoch") plt.ylabel("Accuracy") plt.grid(True)
plt.tight_layout() plt.savefig(save_path) print(f"✅ 训练曲线已保存为: {save_path}")
def save_model(pca_obj, svm_obj, path="model.pkl"): with open(path, "wb") as f: pickle.dump({ 'pca': { 'mean': pca_obj.mean, 'components': pca_obj.components, 'n_components': pca_obj.n_components, }, 'svm': { 'w': svm_obj.w, 'b': svm_obj.b, 'lr': svm_obj.lr, 'epochs': svm_obj.epochs, 'C': svm_obj.C, } }, f) print(f"✅ 模型已保存为: {path}")
if __name__ == "__main__": start_time = time.time()
print("🧾 加载训练图像并增强...") cats_path = 'data/data/train/cats' dogs_path = 'data/data/train/dogs' X, y = load_and_augment_images(cats_path, dogs_path)
print("🔍 提取图像特征...") X_feat = extract_features(X)
print("📐 标准化特征...") X_feat, feat_mean, feat_std = standardize_train(X_feat)
print("📉 进行PCA降维...") pca = PCA(n_components=pca_components) X_reduced = pca.fit_transform(X_feat)
print("🏋️♂️ 训练SVM分类器...") svm = LinearSVM(lr=svm_lr, epochs=svm_epochs, C=svm_C, momentum=momentum) svm.fit(X_reduced, np.array(y))
print("🔎 评估训练准确率...") y_pred = svm.predict(X_reduced) acc = np.mean(y_pred == np.array(y)) print(f"✅ 最终训练准确率: {acc:.4f}")
print("📊 绘制训练误差与准确率图...") plot_training_curve(svm.loss_history, svm.acc_history)
print("💾 保存 PCA 和 SVM 模型...") save_model(pca, svm)
elapsed = time.time() - start_time print(f"\n⏱️ 总训练耗时: {elapsed:.2f} 秒") print("📁 加载测试集...") X_test, y_test, filenames = load_images_for_prediction( cat_dir="data/data/test/cats", dog_dir="data/data/test/dogs", image_size=(128, 128) ) print("🔎 提取测试特征...") X_test_feat = extract_features(X_test) X_test_feat = standardize_test(X_test_feat, feat_mean, feat_std) X_test_pca = pca.transform(X_test_feat) print("📈 测试集预测中...") y_pred = svm.predict(X_test_pca)
print("📄 保存预测结果至 Excel...") df = pd.DataFrame({ "filename": filenames, "predicted_label": y_pred }) df.to_csv("prediction_results.csv", index=False) print("✅ 已保存至 svm_test_predictions.csv")
acc = np.mean(y_pred == np.array(y_test)) print(f"✅ 测试集准确率: {acc:.4f}") print(f"⏱️ 总耗时: {time.time() - start_time:.2f} 秒")
|