def GreedyCycle(distanceMatrix, startingVertex): path = [startingVertex] for i in range(math.ceil(len(distanceMatrix) / 2)): minCost = np.uint64(-1) minCostIndex = -1 vertexToAdd = -1 for j, item in enumerate(range(len(distanceMatrix))): if item not in path: for n in range(len(path)): distance1 = distanceMatrix[item][path[n - 1]] distance2 = distanceMatrix[item][path[n]] cost = distance1 + distance2 - distanceMatrix[path[n - 1]][ path[n]] if cost < minCost: minCostIndex = n vertexToAdd = item minCost = cost path.insert(minCostIndex, vertexToAdd) path = path + [path[0]] return path if __name__ == '__main__': kroA100Data = utils.readTspFile("../data/kroA100.tsp") kroB100Data = utils.readTspFile("../data/kroB100.tsp") utils.tester(GreedyCycle, kroA100Data)
loss_list = [] n_neuron_list = [10,20,30] print("1") n_neuron = 30 n_neuron_2 = 10 model = MLP_Classifier(input_size,n_neuron,n_neuron_2,output_size) criterion = nn.BCELoss() optimizer = optim.SGD(model.parameters(),lr = lr) for i in range(epochs): if i % 100 == 0: print(i) for batch_idx, samples in enumerate(dataloader): x_train_data, y_train_data = samples optimizer.zero_grad() pred = model(x_train_data) loss = criterion(pred,y_train_data) loss.backward() optimizer.step() loss_list.append(loss.detach().numpy()) fig, ax = plt.subplots(figsize = (20,20)) ax.plot(loss_list) print("3") trained_dict = model.state_dict() model = MLP_Classifier(input_size,n_neuron,n_neuron_2,output_size).to(device) tester(x_test_data, y_test_data, model, trained_dict) print("4")
def Regret(distanceMatrix, startingVertex): path = [startingVertex] for i in range(math.ceil(len(distanceMatrix) / 2)): vertexesCosts = [] for item in range(len(distanceMatrix)): costList = [] if item not in path: for n in range(len(path)): distance1 = distanceMatrix[item][path[n - 1]] distance2 = distanceMatrix[item][path[n]] cost = distance1 + distance2 - distanceMatrix[path[n - 1]][ path[n]] costList.append((cost, n)) costList = sorted(costList, key=lambda e: e[0])[0:3] vertexesCosts.append((item, costList[0][1], sum([ costList[i][0] - costList[0][0] for i in range(len(costList)) ]))) vertex, index, _ = max(vertexesCosts, key=lambda e: e[2]) path.insert(index, vertex) path = path + [path[0]] return path if __name__ == '__main__': kroA100Data = utils.readTspFile("../data/kroA100.tsp") kroB100Data = utils.readTspFile("../data/kroB100.tsp") utils.tester(Regret, kroA100Data)