Advertisement
11eimilia11

Funcoes ml

Jan 15th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.60 KB | None | 0 0
  1. import pandas as pd
  2. import cv2
  3. from sklearn import preprocessing
  4. from sklearn.neighbors import KNeighborsClassifier
  5. from scipy import stats
  6. from sklearn.naive_bayes import GaussianNB
  7. from sklearn.tree import DecisionTreeClassifier
  8. from sklearn.svm import SVC
  9. import statistics
  10. from sklearn.metrics import pairwise_distances_argmin_min
  11. import numpy as np
  12. from random import randint
  13. import matplotlib.pyplot as plt
  14. import numpy as np
  15. import cv2
  16. from sklearn.decomposition import PCA
  17. import glob
  18. from sklearn.metrics import pairwise_distances_argmin_min
  19.  
  20. from sklearn.metrics import accuracy_score
  21. from operator import itemgetter
  22.  
  23.  
  24. # função que calcula a quantidade de elementos por classe
  25. # a partir do data frame original, o nome da classe e a classificação
  26.  
  27. def quantidade_por_classe (dados, nome_classe, classe):
  28.     cont = 0
  29.     for x in range(len(dados.index)):
  30.         if (dados[nome_classe].iloc[x] == classe):
  31.             cont += 1
  32.     return cont
  33. # função de inicialização do algoritmo KNN , recebe o k
  34. # e a distância que vai ser usada como referência
  35.  
  36. def inicializacao_KNN (k):
  37.  
  38.     knn = KNeighborsClassifier(n_neighbors=k, metric='euclidean')
  39.     return knn
  40.  
  41.  
  42. # função de normalização dos dados usando o modelo de
  43. # normalização por reescala
  44.  
  45. def normalizar(dados):
  46.     x = dados.values
  47.     min_max_scaler = preprocessing.MinMaxScaler()
  48.     x_scaled = min_max_scaler.fit_transform(x)
  49.     dados_norm = pd.DataFrame(x_scaled)
  50.     return dados_norm
  51.  
  52. # função que calcula os valores de média, moda , mediana e desvio padrão
  53. # para os vetores de acerto de um algoritmo, recebe como parâmetro o vetor
  54. # de acerto e o nome do algoritmo
  55.  
  56. def tendencia_central (nomeAlgoritmo, vetorAcerto, vetorTempo):
  57.     print('________________________________________________\n')
  58.     print(nomeAlgoritmo)
  59.     print('Tempo Média = ', np.mean(vetorTempo))
  60.     print('Tempo Desvio padrão = ', statistics.pstdev(vetorTempo))
  61.     print('Tempo Moda = ', stats.mode(vetorTempo, axis=None))
  62.     print('Tempo Mediana =', np.median(vetorTempo))
  63.     print('----------------------------------------------')
  64.     print('Acurácia Média = ', np.mean(vetorAcerto))
  65.     print('Acurácia Desvio padrão = ', statistics.pstdev(vetorAcerto))
  66.     print('Acurácia Moda = ', stats.mode(vetorAcerto, axis=None))
  67.     print('Acurácia Mediana = ', np.median(vetorAcerto))
  68.  
  69.     print('________________________________________________\n')
  70.  
  71. # função que cria amostras estratificadas a partir
  72. # dos Data frame, o tamanho desejado para a amostra
  73. # e a classe dos dados
  74.  
  75. def amostra_estrat(dados, tamanho_amostra, classe):
  76.     classes = dados[classe].unique()
  77.     qtde_por_classe = round(tamanho_amostra / len(classes))
  78.     amostras_por_classe = []
  79.     for c in classes:
  80.         indices_c = dados[classe] == c
  81.         obs_c = dados[indices_c]
  82.         amostra_c = obs_c.sample(qtde_por_classe)
  83.         amostras_por_classe.append(amostra_c)
  84.  
  85.     amostra_estratificada = pd.concat(amostras_por_classe)
  86.     return amostra_estratificada
  87.  
  88. # função que realiza o treinamento dos algoritmos usados na base de dados
  89.  
  90. def treinaralgoritmos(noclass_train, class_train , tree, knnp1 , knnp2 , knnp3, knn1 , knn2 , knn3, naive, svmlinear , svmrbf):
  91.  
  92.     knn1.fit(noclass_train, class_train)
  93.     knn2.fit(noclass_train, class_train)
  94.     knn3.fit(noclass_train, class_train)
  95.     naive.fit(noclass_train, class_train)
  96.     tree.fit(noclass_train, class_train)
  97.     knnp1.fit(noclass_train, class_train)
  98.     knnp2.fit(noclass_train, class_train)
  99.     knnp3.fit(noclass_train, class_train)
  100.     svmlinear.fit(noclass_train, class_train)
  101.     svmrbf.fit(noclass_train, class_train)
  102.  
  103. # função de inicialização do algoritmo KNN Ponderado
  104. # recebe como parâmentro o valor do k
  105.  
  106. def inicializando_KNNW (k):
  107.  
  108.     knnp = KNeighborsClassifier(n_neighbors=k, weights='distance', metric='euclidean')
  109.     return knnp
  110.  
  111.  
  112.  
  113. def geneticlabels(dataframe,centers):
  114.     return pairwise_distances_argmin_min(dataframe,centers,metric='minkowski')
  115.  
  116. def find_clusters(X, n_clusters, rng, max_it):
  117.  
  118.     i = rng.permutation(X.shape[0])[:n_clusters]
  119.     centers = X[i]
  120.  
  121.     max_iterator = 0
  122.     distances = []
  123.     while True:
  124.  
  125.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  126.         distances.append(distance)
  127.  
  128.         new_centers = np.array([X[labels == i].mean(0)
  129.                                 for i in range(n_clusters)])
  130.  
  131.  
  132.         if np.all(centers == new_centers) or max_iterator > max_it:
  133.             break
  134.         centers = new_centers
  135.         max_iterator += 1
  136.  
  137.     return centers, labels, distances
  138.  
  139.  
  140. def find_clustersGENETIC(X, n_clusters, max_it, array):
  141.  
  142.     centers = array
  143.  
  144.     max_iterator = 0
  145.     distances = []
  146.     while True:
  147.  
  148.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  149.         distances.append(distance)
  150.  
  151.         new_centers = np.array([X[labels == i].mean(0)
  152.                                 for i in range(n_clusters)])
  153.  
  154.  
  155.         if np.all(centers == new_centers) or max_iterator > max_it:
  156.             break
  157.         centers = new_centers
  158.         max_iterator += 1
  159.  
  160.     return centers, labels, distances
  161.  
  162. # Carregando fotos da pasta
  163. def loadFiles(path, array):
  164.  
  165.     for i in glob.glob(path):
  166.  
  167.         img = cv2.imread(i)
  168.         array.append(img)
  169.  
  170.     return array
  171.  
  172. # Função que aplic o filtro blur nas fotos do array
  173. def blurConversion(arrayphotos ,val1, val2):
  174.  
  175.     for x in range(len(arrayphotos)):
  176.         arrayphotos[x] = cv2.GaussianBlur(arrayphotos[x],(val1,val1), val2)
  177.  
  178.     return arrayphotos
  179.  
  180. #Função que faz a binarização das fotos
  181. def binaryConversion(arrayphotos,threshold,val1):
  182.  
  183.     for x in range(len(arrayphotos)):
  184.         arrayphotos[x] = cv2.adaptiveThreshold(arrayphotos[x],threshold,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,val1,10)
  185.  
  186.     return arrayphotos
  187.  
  188. #Função que inverte as fotos binárias
  189. def invertConversion(arrayphotos):
  190.  
  191.     for x in range(len(arrayphotos)):
  192.         arrayphotos[x] = cv2.bitwise_not(arrayphotos[x])
  193.  
  194.     return arrayphotos
  195.  
  196. # Função que faz o filtro cinza nas fotos
  197. def grayConversion(arrayphotos):
  198.  
  199.     size = len(arrayphotos)
  200.     for x in range (0,size):
  201.         arrayphotos[x] = cv2.cvtColor(arrayphotos[x], cv2.COLOR_BGR2GRAY)
  202.  
  203.     return arrayphotos
  204.  
  205. # Função de extração de características
  206. def extractCarac (imagensVector):
  207.     shapesTotal = []
  208.     for i in imagensVector:
  209.         shape1 = []
  210.         im2, contours, hierarchy = cv2.findContours(i, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  211.  
  212.         perimeter = cv2.arcLength(contours[0], True)
  213.  
  214.         approx = cv2.approxPolyDP(contours[0], 0.04*perimeter, True)
  215.  
  216.         #area = cv2.contourArea(contours[0])
  217.  
  218.         #shape1.append(area)
  219.         shape1.append(perimeter)
  220.         shape1.append(len(approx))
  221.  
  222.         m = cv2.moments(i)
  223.         #cX = int((m['m10']/m['m00']))
  224.         #cY = int((m['m01']/m['m00']))
  225.  
  226.         #shape1.append(cX)
  227.         #shape1.append(cY)
  228.  
  229.         moments = cv2.HuMoments(m, True).flatten()
  230.  
  231.         for x in moments:
  232.             shape1.append(x)
  233.  
  234.         shapesTotal.append(shape1)
  235.  
  236.     return shapesTotal
  237.  
  238. def WCSSgenetic(x, population):
  239.  
  240.     arrayint = []
  241.     for a in x:
  242.         arrayint.append(int(a))
  243.  
  244.     print(arrayint)
  245.     soma = 0
  246.     for b in arrayint:
  247.         labels, distances = pairwise_distances_argmin_min(population[b],population, metric='minkowski')
  248.         for x in distances:
  249.             soma += x**2
  250.     return soma
  251.  
  252.  
  253. def generatepopulation(X,numberpopu, K, rng):
  254.  
  255.     population = []
  256.  
  257.     for x in range(numberpopu):
  258.         first = rng.permutation(X.shape[0])[:K]
  259.         print(first)
  260.         population.append(np.concatenate(X[first]))
  261.  
  262.     return population
  263.  
  264.  
  265. def find_clusters(X, n_clusters, rng, max_it):
  266.  
  267.     i = rng.permutation(X.shape[0])[:n_clusters]
  268.     centers = X[i]
  269.  
  270.     max_iterator = 0
  271.     distances = []
  272.     while True:
  273.  
  274.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  275.         distances.append(distance)
  276.  
  277.         new_centers = np.array([X[labels == i].mean(0)
  278.                                 for i in range(n_clusters)])
  279.  
  280.         if np.all(centers == new_centers) or max_iterator > max_it:
  281.             break
  282.         centers = new_centers
  283.         max_iterator += 1
  284.  
  285.     return centers, labels, distances
  286.  
  287.  
  288. def find_clustersgenetic(X, n_clusters, max_it, array):
  289.  
  290.     centers = array
  291.  
  292.     max_iterator = 0
  293.     distances = []
  294.     while True:
  295.  
  296.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  297.         distances.append(distance)
  298.  
  299.         new_centers = np.array([X[labels == i].mean(0)
  300.                                 for i in range(n_clusters)])
  301.  
  302.         if np.all(centers == new_centers) or max_iterator > max_it:
  303.             break
  304.         centers = new_centers
  305.         max_iterator += 1
  306.  
  307.     return centers, labels, distances
  308.  
  309.  
  310. #FUNÇÃO DE NORMALIZAÇÃO
  311.  
  312.  
  313. def normalize(df1):
  314.     x = df1.values.astype(float)
  315.     min_max_scaler = preprocessing.MinMaxScaler()
  316.     scaled = min_max_scaler.fit_transform(x)
  317.     df_normalized = pd.DataFrame(scaled)
  318.     return df_normalized
  319.  
  320. def normalizearray(array):
  321.     scaled = preprocessing.MinMaxScaler().fit_transform(array)
  322.     return scaled
  323.  
  324. def normalizeArrayofArrays(arrayphotos):
  325.  
  326.     size = len(arrayphotos)
  327.     for x in range (0,size):
  328.         arrayphotos[x] = preprocessing.MinMaxScaler().fit_transform(arrayphotos[x])
  329.  
  330.     return arrayphotos
  331.  
  332. def PCAarray(pcanumber, arrayphotos):
  333.  
  334.     pca = PCA(n_components=pcanumber)
  335.     size = len(arrayphotos)
  336.     for x in range (0,size):
  337.         arrayphotos[x] = pca.fit_transform(arrayphotos[x])
  338.  
  339.     return arrayphotos
  340.  
  341. def PCAarrayONLY(pcanumber, arrayphotos):
  342.  
  343.     pca = PCA(n_components=pcanumber)
  344.     arrayphotos = pca.fit_transform(arrayphotos)
  345.  
  346.     return arrayphotos
  347.  
  348. def PCAdataframe(pcanumber,dataframe):
  349.  
  350.     pca = PCA(n_components=pcanumber)
  351.     dataframe = pca.fit_transform(dataframe)
  352.  
  353.     return dataframe
  354.  
  355. def pca1darray(pcanumber,array):
  356.     pca = PCA(n_components=pcanumber)
  357.     pca.fit(array)
  358.     array = pca.transform(array)
  359.  
  360.     return array
  361.  
  362. def Turntogray(arrayphotos):
  363.  
  364.     size = len(arrayphotos)
  365.     for x in range (0,size):
  366.         arrayphotos[x] = cv2.cvtColor(arrayphotos[x], cv2.COLOR_BGR2GRAY)
  367.  
  368.     return arrayphotos
  369.  
  370.  
  371. def reshape2dto1d(arrayphotos):
  372.  
  373.     size = len(arrayphotos)
  374.     for x in range (0,size):
  375.         arrayphotos[x] = arrayphotos[x].ravel()
  376.  
  377.     return arrayphotos
  378.  
  379. def resizephotos(arrayphotos, size1, size2):
  380.  
  381.     size = len(arrayphotos)
  382.     for x in range (0,size):
  383.         arrayphotos[x] = cv2.resize(arrayphotos[x], (size1,size2))
  384.  
  385.     return arrayphotos
  386.  
  387. def gaussianblurArray(arrayphotos,val1,val2):
  388.  
  389.     for x in range(len(arrayphotos)):
  390.         arrayphotos[x] = cv2.GaussianBlur(arrayphotos[x],(val1,val1), val2)
  391.  
  392.     return arrayphotos
  393.  
  394. def binaryadaptive(arrayphotos,threshold,val1):
  395.  
  396.     for x in range(len(arrayphotos)):
  397.         arrayphotos[x] = cv2.adaptiveThreshold(arrayphotos[x],threshold,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,val1,10)
  398.  
  399.     return arrayphotos
  400.  
  401. def invertbinaryphotos(arrayphotos):
  402.  
  403.     for x in range(len(arrayphotos)):
  404.         arrayphotos[x] = cv2.bitwise_not(arrayphotos[x])
  405.  
  406.     return arrayphotos
  407.  
  408.  
  409. def loadfolderimgs(path):
  410.  
  411.     arrayphotos = []
  412.  
  413.     for img in glob.glob(path):
  414.         n = cv2.imread(img)
  415.         arrayphotos.append(n)
  416.  
  417.     return arrayphotos
  418.  
  419.  
  420. def reshape3dto2d(arrayphotos):
  421.  
  422.     size = len(arrayphotos)
  423.     for x in range (0 , size):
  424.         arrayphotos[x] = np.reshape(arrayphotos[x], (arrayphotos[x].shape[0], (arrayphotos[x].shape[1]*arrayphotos[x].shape[2])))
  425.  
  426.     return arrayphotos
  427.  
  428. def imgtoarray(arrayphotos):
  429.  
  430.     size = len(arrayphotos)
  431.     for x in range (0,size):
  432.         arrayphotos[x] = np.array(arrayphotos[x] , dtype=float)
  433.  
  434.     return arrayphotos
  435.  
  436. def sliding_window(image, stepSize, windowSize):
  437.     for y in range(0, image.shape[0], stepSize):
  438.         for x in range(0, image.shape[1], stepSize):
  439.             yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])
  440.  
  441.  
  442. def graphicPCA(pca):
  443.  
  444.     plt.figure()
  445.     plt.plot(np.cumsum(pca.explained_variance_ratio_))
  446.     plt.xlabel('Number of Components')
  447.     plt.ylabel('Variance (%)')  # for each component
  448.     plt.title('Dataset Explained Variance')
  449.     plt.show()
  450.  
  451. def gethumoments(arrayphotos):
  452.  
  453.     for x in range(len(arrayphotos)):
  454.  
  455.         arrayphotos[x] = cv2.HuMoments(cv2.moments(arrayphotos[x]), True).flatten()
  456.  
  457.     return arrayphotos
  458.  
  459. def getHOG(arrayphotos):
  460.  
  461.     for x in range(len(arrayphotos)):
  462.         hog = cv2.HOGDescriptor()
  463.         arrayphotos[x] = hog.compute(arrayphotos[x]).flatten()
  464.  
  465.     return arrayphotos
  466.  
  467. def getHOGplusHU(arrayphotos):
  468.     hog = cv2.HOGDescriptor()
  469.     for x in range(len(arrayphotos)):
  470.         aux = []
  471.  
  472.  
  473.         h = hog.compute(arrayphotos[x]).flatten()
  474.  
  475.         for ho in h:
  476.             aux.append(ho)
  477.  
  478.         hu = cv2.HuMoments(cv2.moments(arrayphotos[x]), True).flatten()
  479.  
  480.         for huu in hu:
  481.             aux.append(huu)
  482.  
  483.         arrayphotos[x] = aux
  484.  
  485.     return arrayphotos
  486.  
  487.  
  488. def getHOGplusHU2(arrayphotos):
  489.  
  490.     hogarray = []
  491.     huarray = []
  492.     hog = cv2.HOGDescriptor()
  493.     for x in range(len(arrayphotos)):
  494.         hogarray.append(hog.compute(arrayphotos[x]).flatten())
  495.  
  496.     hogarray = pd.DataFrame(hogarray)
  497.     hogarray = PCAdataframe(50,hogarray)
  498.  
  499.     for y in range(len(arrayphotos)):
  500.         huarray.append(cv2.HuMoments(cv2.moments(arrayphotos[y]),True).flatten())
  501.  
  502.     for h in range(len(arrayphotos)):
  503.         arrayphotos[h] = np.concatenate((hogarray[h],huarray[h]))
  504.  
  505.     return arrayphotos
  506.  
  507. def extratorcaracteristicafiggeometrica(arrayimgs):
  508.  
  509.     squarescarac = []
  510.  
  511.     for x in arrayimgs:
  512.  
  513.         aux = []
  514.  
  515.         im2, countours, hierachy = cv2.findContours(x, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  516.  
  517.         peri = cv2.arcLength(countours[0], True)  # perimetro
  518.         aux.append(peri)
  519.  
  520.         aproxx = cv2.approxPolyDP(countours[0], 0.04 * peri, True)  # vertices
  521.         vertc = len(aproxx)
  522.         aux.append(vertc)
  523.  
  524.         area = cv2.contourArea(countours[0])  # area
  525.         aux.append(area)
  526.  
  527.         momentum = cv2.moments(x)
  528.  
  529.         #cX = int(momentum["m10"] / momentum["m00"])
  530.         #cY = int(momentum["m01"] / momentum["m00"])
  531.  
  532.         #aux.append(cX)
  533.         #aux.append(cY)
  534.  
  535.         moments = cv2.HuMoments(momentum, True).flatten()
  536.  
  537.         for i in moments:
  538.             aux.append(i)
  539.  
  540.         squarescarac.append(aux)
  541.  
  542.  
  543.     return squarescarac
  544.  
  545. def initialize_dic_majority(classes):
  546.     majority = {}
  547.     for c in classes:
  548.         majority[c] = 0
  549.  
  550.     return majority
  551.  
  552. def accuracy_majority_vote(base, predict_labels, real_labels, n_clusters):
  553.  
  554.     classes = real_labels.unique()
  555.  
  556.     majority = []
  557.     groups = []
  558.     k = 0
  559.     for i in range(n_clusters):
  560.         group = []
  561.         for a in range(len(base)):
  562.             if predict_labels[a] == i:
  563.                 group.append(real_labels[a])
  564.         groups.append(group)
  565.         majority.append(initialize_dic_majority(classes))
  566.         for real_label in group:
  567.             majority[k][real_label] += 1
  568.         k += 1
  569.  
  570.     label_groups = []
  571.     for m in majority:
  572.         label_groups.append(max(m.items(), key=itemgetter(1))[0])
  573.  
  574.     pred_labels = []
  575.     true_labels = []
  576.     for g in range(len(groups)):
  577.         pred_labels = pred_labels + ([label_groups[g]]*len(groups[g]))
  578.         true_labels = true_labels + [a for a in groups[g]]
  579.  
  580.     return accuracy_score(pred_labels, true_labels)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement