def main_circles(): # init data = CirclesData() data.plot_data() np.random.seed(42) N = data.Xtrain.shape[0] inds = np.arange(0, N) np.random.shuffle(inds) Xtrain = data.Xtrain[inds] Ytrain = data.Ytrain[inds] Nbatch = 15 nx = data.Xtrain.shape[1] nh = 10 ny = data.Ytrain.shape[1] eta = 0.03 # Premiers tests, code à modifier model, loss, optim = init_model(nx, nh, ny, eta) writer = SummaryWriter() L, acc = 0, 0 # TODO apprentissage Nepochs = 200 for i in range(Nepochs): for j in range(0, N, Nbatch): Xbatch = Xtrain[j:j + Nbatch] Ybatch = Ytrain[j:j + Nbatch] Yhat = model(Xbatch) L, acc = loss_accuracy(loss, Yhat, Ybatch) # Calcule les gradients optim.zero_grad() L.backward() optim.step() # Loss and Accuracy on Test Yhat_test = model(data.Xtest) L_test, acc_test = loss_accuracy(loss, Yhat_test, data.Ytest) data.plot_loss(L, L_test, acc, acc_test) Ygrid = torch.nn.Softmax(dim=1)(model(data.Xgrid)) data.plot_data_with_grid(Ygrid.detach()) # attendre un appui sur une touche pour garder les figures input("done")
# Premiers tests, code à modifier model, loss = init_model(nx, nh, ny) writer = SummaryWriter() L, acc = 0, 0 # TODO apprentissage Nepochs = 200 for i in range(Nepochs): for j in range(0, N, Nbatch): Xbatch = Xtrain[j:j + Nbatch] Ybatch = Ytrain[j:j + Nbatch] Yhat = model(Xbatch) L, acc = loss_accuracy(loss, Yhat, Ybatch) # Calcule les gradients L.backward() params = sgd(model, eta) # Loss and Accuracy on Test Yhat_test = model(data.Xtest) L_test, acc_test = loss_accuracy(loss, Yhat_test, data.Ytest) data.plot_loss(L, L_test, acc, acc_test) Ygrid = torch.nn.Softmax(dim=1)(model(data.Xgrid)) data.plot_data_with_grid(Ygrid.detach()) # attendre un appui sur une touche pour garder les figures input("done")
accuracy, sep='') # Testing set Yhat, _ = forward(params, torch.from_numpy(data._Xtest)) L, accuracy = loss_accuracy(Yhat, torch.from_numpy(data._Ytest)) print(' Test set:\n', ' loss: ', L.item(), '; accuracy: ', accuracy, sep='') testLosses.append(L.item()) Ygrid, _ = forward(params, data.Xgrid) data.plot_data_with_grid(Ygrid) x = np.arange(0, Nepoch, printInterval) trainLosses = np.array(trainLosses) testLosses = np.array(testLosses) plt.close() plt.clf() plt.ylabel('Losses') plt.xlabel('Epoch') plt.title('Train loss and Test loss with time') plt.grid(True) plt.plot(x, trainLosses, 'b--', x, testLosses, 'r--') plt.legend(['Train loss', 'Test loss'], loc=1) plt.show() # attendre un appui sur une touche pour garder les figures