Advertisement
11eimilia11

Projeto ML p02 tentativa

Jan 3rd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.28 KB | None | 0 0
  1. import pandas as pd
  2. from sklearn.model_selection import KFold
  3. from sklearn.neighbors import KNeighborsClassifier
  4. from sklearn.tree import DecisionTreeClassifier
  5. from sklearn.naive_bayes import GaussianNB
  6. from sklearn.linear_model import LogisticRegression
  7. from sklearn.svm import SVC
  8. from Lista02 import FuncoesML as fun
  9. from scipy import stats
  10. import numpy as np
  11. from random import randint
  12. from sklearn.cluster import KMeans
  13. from Lista03 import pso as pso
  14.  
  15. KCLUSTERS = 4
  16.  
  17. def WCSS(distance):
  18.     retorno = []
  19.     for x in distance:
  20.         soma = 0
  21.         for z in x:
  22.             soma += z ** 2
  23.         retorno.append(soma)
  24.  
  25.     return retorno
  26.  
  27.  
  28. def break_vectors(vector):
  29.     global KCLUSTERS
  30.     retorno = np.split(vector, KCLUSTERS)
  31.     return retorno
  32.  
  33.  
  34. def wcssGenetic(centers):
  35.     global KCLUSTERS
  36.     array = break_vectors(centers)
  37.  
  38.     kmeans = KMeans(KCLUSTERS, init=pd.DataFrame(array), max_iter=1, n_init=1)
  39.     kmeans.fit(pd.DataFrame(df_final))
  40.  
  41.     return kmeans.inertia_
  42.  
  43.  
  44. def generatepopulation(X, numberpopu, K, rng):
  45.     population = []
  46.  
  47.     for x in range(numberpopu):
  48.         first = rng.permutation(X.shape[0])[:K]
  49.         population.append(np.concatenate(X[first]))
  50.  
  51.     return population
  52.  
  53. #Criando a classe receita que irá conter nome, classe e vetor de ingredientes
  54. class Receita:
  55.     Name = None
  56.     Class = 0
  57.     ingredientes = []
  58.     ingredientesnorm = []
  59.  
  60.  
  61. #Método que retorna o vetor de ingredientes
  62.     def getingrednorm(self):
  63.         return self.ingredientesnorm
  64.  
  65. #Construtor da classe receita
  66.     def __init__(self, name, Class, ingredientes):
  67.         self.Name = name
  68.         self.Class = Class
  69.         self.ingredientes = ingredientes
  70.  
  71. #Método que adiciona ingredientes no vetor de ingredientes
  72.     def adicionaringrediente(self, ingrediente):
  73.         self.ingredientes.append(ingrediente)
  74.  
  75. #abrindo o arquivo com a base de dados
  76. reshipe = open("C:/Users/Auricelia/Desktop/DatasetsML/ReshibaseQ.txt", "rt", encoding="utf8")
  77.  
  78. #criando o vetor de receitas
  79. receitas = []
  80.  
  81. # preenchendo o vetor de receitas
  82. for receita in reshipe:
  83.     dividido = receita.split(sep=',')
  84.     dividido[(len(dividido) - 1)] = dividido[(len(dividido) - 1)].replace('\n', '')
  85.     ingredientes = []
  86.  
  87.     for x in range(2, len(dividido)):
  88.         ingredientes.append(dividido[x])
  89.  
  90.     receitas.append(Receita(dividido[1], dividido[0], ingredientes))
  91.  
  92. #vetor que irá receber todos os ingredientes sem repetição para fazer os vetores binários
  93. todosingredientes = []
  94.  
  95. #preenchendo o vetor 'todosingredientes' sem repetição
  96. for rec in receitas:
  97.     for ingrediente in rec.ingredientes:
  98.  
  99.         if todosingredientes.__contains__(ingrediente) == False:
  100.             todosingredientes.append(ingrediente)
  101. #ordenando o vetor
  102. todosingredientes = sorted(todosingredientes)
  103.  
  104. # preenchendo nos objetos receita o vetor binário com 0
  105.  
  106. for rec in receitas:
  107.     norm = []
  108.     for y in range(0, len(todosingredientes)):
  109.         norm.append(0)
  110.     rec.ingredientesnorm = norm
  111.  
  112. # Colocando 1 na posição em que existe o ingrediente
  113.  
  114. for rec in receitas:
  115.     for y in rec.ingredientes:
  116.         pos = todosingredientes.index(y)
  117.         rec.ingredientesnorm[pos] = 1
  118.  
  119. # Vetor que irá receber os vetores binários de ingreientes de cada receita
  120. arrayingredientesnorm = []
  121.  
  122. # Preenchendo o vetor com os ingredientes normalizados
  123.  
  124. for rec in receitas:
  125.     arrayingredientesnorm.append(rec.ingredientesnorm)
  126.  
  127. # Vetor que irá receber as classes de cada receita
  128. arrayclasse = []
  129.  
  130. # preenchendo o vetor com as classes de cada receita
  131. for rec in receitas:
  132.     arrayclasse.append(rec.Class)
  133.  
  134. # criando o dataframe que irá armazenar os ingredientes
  135. df = pd.DataFrame(arrayingredientesnorm)
  136.  
  137. #adicionando a classe ao dataframe
  138. df['Class'] = arrayclasse
  139. lista = df['Class']
  140. del df['Class']
  141. df_final = np.array(df)
  142. print('TAMANHO DF :',df_final[0].size*4)
  143.  
  144. print("VAI COMEÇAR")
  145. resultsKmeans = []              # ARRAY QUE SALVA AS ACURACIAS DO KMEANS
  146. resultKmeansHybrid = []         # ARRAY QUE SALVA AS ACURACIAS DO HYBRID
  147. acuraciaKmeans = []             # ARRAY QUE SALVA O WCSS DO K MEANS
  148. acuraciaHybrid = []             # ARRAY QUE SALVA O WCSS DO HYBRID
  149. for y in range(10):
  150.  
  151.     print("RODADA " + str(y))
  152.     resultparcial = []
  153.     distance = []
  154.     h = randint(1, 10)
  155.     rng = np.random.RandomState(h)
  156.  
  157.     print("-----------------------------------------------")
  158.     for algumacoisa in range(20):                                 # AQUI RODA O KMEANS 20 VEZES
  159.         print("VEZ KMEANS " + str(algumacoisa))
  160.         centers, labels, distance = fun.find_clusters(df_final, KCLUSTERS, rng, 100)        # AQUI VOCE PASSA 4 PARAMETROS, O SEU DATAFRAME EM UM NUMPYARRAY, O NUMERO DE CLASSES, O RNG QUE É A SEED E O NUMERO MAX DE ITERAÇÕES
  161.         print(fun.accuracy_majority_vote(df_final,labels,lista,2))  # PRINTA O VOTO MAJORITARIO, QUE RECEBE SEU DATAFRAME EM FORMA DE ARRAY, OS LABELS DO RETORNO DE CIMA, E A LISTA QUE É A COLUNA DE LABELS DO SEU DATAFRAME ANTES DE VIRAR NUMPYARRAY
  162.         acuraciaKmeans.append(fun.accuracy_majority_vote(df_final,labels,lista,2))
  163.         retorno = WCSS(distance)
  164.         resultparcial.append(retorno[len(retorno) - 1])
  165.  
  166.  
  167.     resultparcial = np.sort(resultparcial)
  168.  
  169.     resultsKmeans.append(resultparcial[0])
  170.  
  171.     population = generatepopulation(df_final, 20, KCLUSTERS, rng)
  172.  
  173.     p = pso(20, wcssGenetic, 0, 200000, 1608, 100, init=population)
  174.     array = np.array(p.get_Gbest())
  175.     array = np.split(array, 4)
  176.  
  177.     print("Hybrid:")
  178.     cen, lbl, dis = fun.find_clustersgenetic(df_final, KCLUSTERS, 100, array)
  179.     print(fun.accuracy_majority_vote(df_final, lbl, lista, 4))
  180.     acuraciaHybrid.append(fun.accuracy_majority_vote(df_final, lbl, lista, 4))
  181.  
  182.     ret = WCSS(dis)
  183.     resultKmeansHybrid.append(ret[len(ret) - 1])
  184.  
  185.     # num = retorno[len(retorno) - 1]
  186.     # dictionary[h] = num
  187.  
  188. #
  189. # print("Distancias" ,distance)
  190.  
  191. resultKmeansHybrid = np.sort(resultKmeansHybrid)
  192. resultsKmeans = np.sort(resultsKmeans)
  193. print("Media Hibrido", np.mean(resultKmeansHybrid))
  194. print("Media sem hibrido", np.mean(resultsKmeans))
  195. print(resultKmeansHybrid)
  196. print("Nao hibrido", resultsKmeans)
  197.  
  198. print("MEDIAS")
  199. print(np.mean(acuraciaKmeans), "ACURACIA KMEANS")
  200. print(np.mean(acuraciaHybrid), "ACURACIA KHYBRID")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement