





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






import random import copy import math
import matplotlib.pyplot as plt POPULATION_SIZE = 20 CITIES_SIZE = 20 TOUR_SIZE = 21 NUM_EXECUTION = 9999 population = [] x = [] y = [] tour = [[0 for x in range(TOUR_SIZE)] for y in range(TOUR_SIZE)] dCidade = [[0 for x in range(POPULATION_SIZE)] for y in range(POPULATION_SIZE)] distances = [0 for x in range(POPULATION_SIZE)] parentsOne = None parentsTwo = None """ Generates the first population """ def generateFirstPopulation():
for _ in range(1, POPULATION_SIZE + 1): generatePossiblePath() """ Method called in the generateFirstPopulation() to generate a new possible path for the population """ def generatePossiblePath(): path = [] for _ in range(1, CITIES_SIZE + 1):
randomNum = random.randint(1, 20)
while(numberExistsInPath(path, randomNum)): randomNum = random.randint(1, 20) path.append(randomNum) population.append(path) """ Method to verify if the number is already in the path """ def numberExistsInPath(path, number): for i in path: if i == number: return True
based on the tour matrix """ def calculateDistances(): global distances distances = [0 for x in range(POPULATION_SIZE)] for i in range(len(population)): for j in range(len(population[i])): firstPos = 19 if tour[i][j] == 20 else tour[i][j] secondPos = 19 if tour[i][j+1] == 20 else tour[i][j+1] distances[i] += round(dCidade[firstPos][secondPos], 4) dict_dist = {i: distances[i] for i in range(0, len(distances))} distances = copy.deepcopy(dict_dist) return sorted(distances.items(), key=lambda kv: kv[1]) """ Generate the identity matrix (dCidade) based on the x and y arrays and then call the calculateDistances() method to generate the array with the sum of each path to user later in the cycle process """ def fitnessFunction(): for i in range(len(population)): for j in range(len(population)): dCidade[i][j] = round(math.sqrt(((x[i] - x[j])2) + ((y[i] - y[j])2)), 4) return calculateDistances() """ Performs the roulette function, generating two arrays with 5 parents each, which will be used later to do the cycle process """ def rouletteFunction(sorted_x): global parentsOne global parentsTwo arr = [] rouletteArr = [] for i in range(10): arr.append(sorted_x[i][0]) for j in range(len(arr)): for _ in range(10 - j): rouletteArr.append(arr[j]) parentsOne = createParents(rouletteArr) parentsTwo = createParents(rouletteArr) """ Auxiliary method used in the rouletteFunction() to generate the two parents array """
def createParents(rouletteArr): parentArr = [] for _ in range(5): parentArr.append(rouletteArr[random.randint(0, 54)]) return parentArr """ Method used in the cycle method to see if there's any duplicated city """ def hasDuplicity(auxArray, usedIndexes): for i in range(len(auxArray)): for j in range(i, len(auxArray)): if i != j and auxArray[i] == auxArray[j]: if i in usedIndexes: return j else: return i return - """ Method that has the 'cycle' logic.
sorted_x = fitnessFunction() print('Total Population: %s' % (POPULATION_SIZE)) print('Mutation probability: 5%') print('Number of cities: %s' % (CITIES_SIZE)) print('Optimal path cost: %s' % sorted_x[0][1]) print('Best route: %s' % population[0]) if name == "main": main()
from sklearn.datasets import fetch_20newsgroups categories = ['alt.atheism', 'soc.religion.christian','comp.graphics', 'sci.med','sci.space'] news_train = fetch_20newsgroups (subset = 'train', categories= categories, shuffle= True) news_test = fetch_20newsgroups (subset = 'test',categories= categories, shuffle= True) from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB text_clf = Pipeline ([('vect', TfidfVectorizer()), ('clf', MultinomialNB()) ])
text_clf.fit (news_train.data, news_train.target)
predicted = text_clf.predict(news_test.data)
from sklearn import metrics from sklearn.metrics import accuracy_score import numpy as np print ('Accuracy achieved is ' + str(np.mean(predicted == news_test.target))) print(metrics.classification_report(news_test.target, predicted, target_names=news_test.target_names)), metrics.confusion_matrix(news_test.target, predicted) def predict_category(s,train=news_train, model=text_clf): pred = model.predict([s]) return train.target_names[pred[0]]