()
| 253 | |
| 254 | |
| 255 | def benchmark_pca(): |
| 256 | Xtrain, Xtest, Ytrain, Ytest = get_transformed_data() |
| 257 | print("Performing logistic regression...") |
| 258 | |
| 259 | N, D = Xtrain.shape |
| 260 | Ytrain_ind = np.zeros((N, 10)) |
| 261 | for i in range(N): |
| 262 | Ytrain_ind[i, Ytrain[i]] = 1 |
| 263 | |
| 264 | Ntest = len(Ytest) |
| 265 | Ytest_ind = np.zeros((Ntest, 10)) |
| 266 | for i in range(Ntest): |
| 267 | Ytest_ind[i, Ytest[i]] = 1 |
| 268 | |
| 269 | W = np.random.randn(D, 10) / np.sqrt(D) |
| 270 | b = np.zeros(10) |
| 271 | LL = [] |
| 272 | LLtest = [] |
| 273 | CRtest = [] |
| 274 | |
| 275 | # D = 300 -> error = 0.07 |
| 276 | lr = 0.0001 |
| 277 | reg = 0.01 |
| 278 | for i in range(200): |
| 279 | p_y = forward(Xtrain, W, b) |
| 280 | # print "p_y:", p_y |
| 281 | ll = cost(p_y, Ytrain_ind) |
| 282 | LL.append(ll) |
| 283 | |
| 284 | p_y_test = forward(Xtest, W, b) |
| 285 | lltest = cost(p_y_test, Ytest_ind) |
| 286 | LLtest.append(lltest) |
| 287 | |
| 288 | err = error_rate(p_y_test, Ytest) |
| 289 | CRtest.append(err) |
| 290 | |
| 291 | W += lr*(gradW(Ytrain_ind, p_y, Xtrain) - reg*W) |
| 292 | b += lr*(gradb(Ytrain_ind, p_y) - reg*b) |
| 293 | if i % 10 == 0: |
| 294 | print("Cost at iteration %d: %.6f" % (i, ll)) |
| 295 | print("Error rate:", err) |
| 296 | |
| 297 | p_y = forward(Xtest, W, b) |
| 298 | print("Final error rate:", error_rate(p_y, Ytest)) |
| 299 | iters = range(len(LL)) |
| 300 | plt.plot(iters, LL, iters, LLtest) |
| 301 | plt.show() |
| 302 | plt.plot(CRtest) |
| 303 | plt.show() |
| 304 | |
| 305 | |
| 306 | if __name__ == '__main__': |
nothing calls this directly
no test coverage detected