sexta-feira, 16 de dezembro de 2022

LDA com iris

 import numpy as np

class LDA:

    def __init__(self, n_components):

        self.n_components = n_components

        self.linear_discriminants = None

    def fit(self, x, y):

        n_features = x.shape[1]

        class_labels = np.unique(y)

        mean_overall = np.mean(x, axis=0)

        S_W = np.zeros((n_features,n_features))

        S_B = np.zeros((n_features,n_features))

        for c in class_labels:

            X_c = x[y==c]

            mean_c = np.mean(X_c, axis=0)

            S_W+= (X_c - mean_c).T.dot(X_c-mean_c)

            n_c = X_c.shape[0]

            mean_diff = (mean_c - mean_overall).reshape(n_features,1)

            S_B += n_c*(mean_diff).dot(mean_diff.T)

        A = np.linalg.inv(S_W).dot(S_B)

        eigenvalues, eigenvectors = np.linalg.eig(A)

        eigenvectors = eigenvectors.T

        idxs= np.argsort(abs(eigenvalues))[::-1]

        eigenvalues = eigenvalues[idxs]

        eigenvectors = eigenvectors[idxs]

        self.linear_discriminants = eigenvectors[0:self.n_components]

        

    def transform (self, x):

        return np.dot(x, self.linear_discriminants.T)


#### pra ser igual do PCA

from sklearn import datasets

#pip install lda

import matplotlib.pyplot as plt

#import numpy as np

#from lda import LDA

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA



data = datasets.load_iris()

x=data.data

y=data.target


lda= LDA(2) #(dois exios)

lda.fit (x,y)

X_projected = lda.transform(x)


print ('shape of x', x.shape)

print ('shape of transformed x:', X_projected.shape)


x1 = X_projected[:,0]

x2 = X_projected[:,1]

plt.scatter (x1,x2,c=y, edgecolor='none', alpha=0.8, cmap=plt.cm.get_cmap('viridis',3))

plt.xlabel('linear discriminant 1')

plt.ylabel('linear discriminant 2')

plt.colorbar()

plt.show()

domingo, 9 de outubro de 2022

Ponto no poligono

 import geopandas as gpd 

gpda = gpd.read_file('arquivo.json', driver='GeoJSON') 

import fiona

gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = 'rw'

df = gpd.read_file('arquivo.kml', driver='KML')

dg=df['geometry']

env = gpda['geometry']

env.contains(dg)#The indices of the two GeoSeries are different.

Mapas de calor e outros

 import geopandas as gpd 

import matplotlib.pyplot as plt

gdf_geometrias_gsp = gpd.read_file('SP_Municipios_2020.shp') #arquivo de referencia

gdf_geometrias_gsp.head

shape2=['geometry'] #nome da coluna

data_2= shape[shape['NM_MUN']=='São Paulo'] #dados do arquiv de referencia

data_2.plot()

filename='dados_capital_sp.json'

print(data_2['geometry'])

data_2.to_file(filename, driver ="GeoJSON")

df_roubo=pd.read_excel('Celular.xlsx')

df_roubo.dropna(subset=['LATITUDE','LONGITUDE'])

df_roubo[['LATITUDE', 'LONGITUDE']]

df_roubo['geometry']=None

type(df_roubo)

for index, row in df_roubo.iterrows():

    df_roubo.loc[index,'geometry'] = Point(row.LONGITUDE, row.LATITUDE) #esse põem pontos

gdf_roubos= gpd.GeoDataFrame(df_roubo, geometry='geometry') 

gdf_roubos.plot()

gpd_capital_spp = gpd.read_file('dados_capital_sp.json', driver='GeoJSON')

import matplotlib.pyplot as plt 

polygon_sp= gpd_capital_spp.iloc[0].geometry

gdf_roubos_capital = gdf_roubos['geometry'].intersection(polygon_sp)

gdf_roubos_capital.plot()

gdf_roubos.plot()

gpd_capital_sp.plot()

import folium

fmap = folium.Map()

fig.ax = plt.subplots(figsize=(10,10))

gdf_roubos_capital.plot(ax=ax)

gpd_capital_sp.plot(ax=ax, facecolor='None', edgecolor='Black')

polygon_sp.plot(ax=ax, facecolor='None', edgecolor='Black')

import webbrowser

webbrowser.open("fmap.html")

gdf_roubos_capital.to_file('mapa1.json', driver ="GeoJSON") 

gdf_roubos.dropna(subset=["LATITUDE", "LONGITUDE"], inplace=True)

gdf_roubo_capital = gpd.read_file('mapa1.json', driver='GeoJSON')

gdf_roubos_capital_slice = gdf_roubo_capital.iloc[:100]# só 100 primeiros

gdf_roubos_slice = gdf_roubo.iloc[:100]

gdf_roubos_capital_slice.crs = "EPSG:29101"

medialat = gdf_roubos['LATITUDE'].mean() 

medialong = gdf_roubos['LONGITUDE'].mean()

fmap = folium.Map(location=[medialat, medialong])

feat_geojson=folium.features.GeoJson(gdf_roubos_capital_slice)

fmap.add_child(feat_geojson) #juntando os dados

fmap.save("fmap1.html")

webbrowser.open("fmap1.html")



from folium.plugins import FastMarkerCluster

fmap = folium.Map(location=[medialat, medialong])

mc=FastMarkerCluster=FastMarkerCluster(gdf_roubos[['LATITUDE','LONGITUDE']])

fmap.add_child(mc)

fmap.save("fmap2.html")

webbrowser.open("fmap2.html")

gdf_geometrias_gsp#limites dos municipios

limites=folium.features.GeoJson(gdf_geometrias_gsp, style_function=lambda feature:{'color': 'black', 'weight': '2', 'fillOpacity': '0.0'} )

fmap.add_child(limites)

from folium.plugins import HeatMap

fmap = folium.Map(location=[medialat, medialong], title ='cartodbpositron')

HeatMap = HeatMap (gdf_roubos[['LATITUDE','LONGITUDE']])

fmap.add_child(HeatMap)

fmap.save("fmap3.html")

webbrowser.open("fmap3.html")


for index, municipio in gdf_geometrias_gsp.iterrows():

    qtd_roubos = len(gdf_roubos[gdf_roubos.intersects(municipio.geometry)])

    gdf_geometrias_gsp.loc[index,'qtd_roubos']=qtd_roubos


media_latitude_gsp = gdf_roubos['LATITUDE'].mean()

media_longitude_gsp=gdf_roubos['LONGITUDE'].mean()

fmap = folium.Map(locations=[media_latitude_gsp, media_longitude_gsp],titles='cartodbpositron')



for _, municipios in gdf_geometrias_gsp.iterrows():

    municipio_geojson = folium.features.GeoJson(municipio.geometry, style_function = lambda feature:{'color':'blue', 'weinght': '2', 'fillOpacity':0.1})

    popup=folium.Popup("""Municipios:{} Roubo registrados em Novembro: {}""".format(municipio.NM_MUN, str(int(municipio.qtd_roubos)))) #'Series' object has no attribute

popup.add_to(municipio_geojson)

municipio_geojson.add_to(fmap)

fmap.save("fmap4.html")

webbrowser.open("fmap4.html")





sexta-feira, 2 de setembro de 2022

PCA/LDA - convex hulls

 

#PCA

import pandas as pd

import numpy as np

from sklearn import datasets

from scipy.spatial import ConvexHull, convex_hull_plot_2d

import matplotlib.pyplot as plt

from sklearn.preprocessing import StandardScaler


#from sklearn.decomposition import PCA

#LDA

#pip install lda

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA


#inicio

scaler = StandardScaler()

##

class LDAs:

    def __init__(self, n_components):

        self.n_components = n_components

        self.linear_discriminants = None

    def fit(self, x, y):

        n_features = x.shape[1]

        class_labels = np.unique(y)

        mean_overall = np.mean(x, axis=0)

        S_W = np.zeros((n_features,n_features))

        S_B = np.zeros((n_features,n_features))

        for c in class_labels:

            X_c = x[y==c]

            mean_c = np.mean(X_c, axis=0)

            S_W+= (X_c - mean_c).T.dot(X_c-mean_c)

            n_c = X_c.shape[0]

            mean_diff = (mean_c - mean_overall).reshape(n_features,1)

            S_B += n_c*(mean_diff).dot(mean_diff.T)

        A = np.linalg.inv(S_W).dot(S_B)

        eigenvalues, eigenvectors = np.linalg.eig(A)

        eigenvectors = eigenvectors.T

        idxs= np.argsort(abs(eigenvalues))[::-1]

        eigenvalues = eigenvalues[idxs]

        eigenvectors = eigenvectors[idxs]

        self.linear_discriminants = eigenvectors[0:self.n_components]

        print(self.linear_discriminants)

        

    def transform (self, x):

        return np.dot(x, self.linear_discriminants.T)

#Abrindo CSV

#data = datasets.load_iris() #iris

df= pd.read_csv('EBIs.csv', names=['target','CPOD','CED','CPD','CEA','CBDIA','CESC','CEIC ','CAC','CBD','CC','DO','DEN','CF','DI','CRM','ASO','COP','LD','AD','DLNB','CEPeitoral','CT','CA','CENA','CPC','Lcie','LSC','CEPelvica','APC'])

features = ['CPOD','CED','CPD','CEA','CBDIA','CESC','CEIC ','CAC','CBD','CC','DO','DEN','CF','DI','CRM','ASO','COP','LD','AD','DLNB','CEPeitoral','CT','CA','CENA','CPC','Lcie','LSC','CEPelvica','APC']



#X=data.data #iris

#Y=data.target #iris

x = df.loc[:, features].values #mesmo que x do iris

y = df.values[:,0] #values #esse são todos os nomes repetidas vezes([])

target = set(y) #mesmo que target {} ta diferente


#pca = PCA(n_components=2) #dois eixos

lda= LDAs(2) #(dois exios)

#principalComponents = pca.fit_transform(x)


#trava aqui

#teste

#xs = x*100

#xs=xs.astype('int')



lda.fit (x,y) 

X_projected = lda.transform(x) 



#hull = ConvexHull(principalComponents)#PCA

hull = ConvexHull(X_projected)#LDA


colors = ['r','blue', 'orange', 'green', 'green','green','green','green','green', 'green']

lw=2




#hulls LDA#



for color, i  in zip(colors, [1., 2., 9., 4., 5., 6.,7.,8.,3.,10.]):#nos colchetes o nome deve estar igual ao 'nomes'

    plt.scatter(X_projected[y == i, 0], X_projected[y == i, 1], color=color)

    hull = ConvexHull(X_projected[y == i])

    for simplex in hull.simplices:

        plt.plot(X_projected[y == i][simplex, 0], X_projected[y==i][simplex, 1], 'k-')

        plt.xlabel('LD 1')

        plt.ylabel('LD 2')

resultado:





Arquivo csv (modelo)



Criando mapas html (Open map)

from tkinter import *

import os, sys

root = Tk()


class mapa ():#

    def __init__ (self):

        import folium

        import json

        import webbrowser

       

        from folium import plugins

        mapatotal=folium.Map(location=[-30.0,-54.0], zoom_start=4, control_scale=True)

       

        mapatotal.add_child(folium.LatLngPopup())

        

        camadasub1=plugins.FeatureGroupSubGroup(mapatotal,'Bryconamericus_uporas', show=False)

        mapatotal.add_child(camadasub1)

        camadasub2=plugins.FeatureGroupSubGroup(mapatotal,'Bunocephalus_doriae', show=False)

        mapatotal.add_child(camadasub2)


        folium.GeoJson('Bryconamericus_uporas.json').add_to(camadasub1)

        folium.GeoJson('Bunocephalus_doriae.json').add_to(camadasub2)

        folium.LayerControl(collapsed=True).add_to(mapatotal)#show nã muda nada

        mapatotal.save("mapa2.html")

        webbrowser.open("mapa2.html")

        


menu =  Menu(root)

root.title("Widholzer.R.L")

root.config(menu=menu)


subMenu = Menu(menu)


menu.add_cascade(label="Inicio",menu=subMenu)


subMenu.add_command(label="Open map", command= mapa)

oy)

editMenu = Menu(menu)

Menu1=[]

SubMenu1=[]


root.mainloop() 




Tkinter mensagens

 import tkinter.messagebox

from tkinter import *

windows=Tk()

# Let's create a alert box with 'messagebox' function

tkinter.messagebox.showinfo("Alert Message", "This is just a alert message!")


# Let's also create a question for the user and based upon the response [Yes or No Question] display a message.

response = tkinter.messagebox.askquestion("Tricky Question", "Do you love Deep Learning?")

print(response)

# A basic 'if/else' block where if user clicks on 'Yes' then it returns 1 else it returns 0. For each response you will display a message with the help of 'Label' method.

if response == 'yes':

    tkinter.Label(windows, text = "Yes, offcourse I love Deep Learning!").pack()

else:

    tkinter.Label(windows, text = "No, I don't love Deep Learning!").pack()


windows.mainloop()