Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

evaluacion PCA python

#importamos librerías
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (16, 9)
plt.style.use('ggplot')
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
 
#cargamos los datos de entrada
dataframe = pd.read_csv(r"comprar_alquilar.csv")
print(dataframe.tail(10))
 
#normalizamos los datos
scaler=StandardScaler()
df = dataframe.drop(['comprar'], axis=1) # quito la variable dependiente "Y"
scaler.fit(df) # calculo la media para poder hacer la transformacion
X_scaled=scaler.transform(df)# Ahora si, escalo los datos y los normalizo
 
#Instanciamos objeto PCA y aplicamos
pca=PCA(n_components=9) # Otra opción es instanciar pca sólo con dimensiones nuevas hasta obtener un mínimo "explicado" ej.: pca=PCA(.85)
pca.fit(X_scaled) # obtener los componentes principales
X_pca=pca.transform(X_scaled) # convertimos nuestros datos con las nuevas dimensiones de PCA
 
print("shape of X_pca", X_pca.shape)
expl = pca.explained_variance_ratio_
print(expl)
print('suma:',sum(expl[0:5]))
#Vemos que con 5 componentes tenemos algo mas del 85% de varianza explicada
 
#graficamos el acumulado de varianza explicada en las nuevas dimensiones
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
plt.show()
 
#graficamos en 2 Dimensiones, tomando los 2 primeros componentes principales
Xax=X_pca[:,0]
Yax=X_pca[:,1]
labels=dataframe['comprar'].values
cdict={0:'red',1:'green'}
labl={0:'Alquilar',1:'Comprar'}
marker={0:'*',1:'o'}
alpha={0:.3, 1:.5}
fig,ax=plt.subplots(figsize=(7,5))
fig.patch.set_facecolor('white')
for l in np.unique(labels):
    ix=np.where(labels==l)
    ax.scatter(Xax[ix],Yax[ix],c=cdict[l],label=labl[l],s=40,marker=marker[l],alpha=alpha[l])
 
plt.xlabel("First Principal Component",fontsize=14)
plt.ylabel("Second Principal Component",fontsize=14)
plt.legend()
plt.show()
Comment

PREVIOUS NEXT
Code Example
Python :: python nltk lookup error Resource omw-1.4 not found. 
Python :: # difference between list 1 and list 2 
Python :: iloc vs iat 
Python :: turn of legend pairplot 
Python :: get weather data from weather underground 
Python :: Default rows values display 
Python :: python bitcoin prices 
Python :: Count the data points based on columns 
Python :: turn index back to column 
Python :: split list in two based on condition python 
Python :: Python Anagram Using Counter() function 
Python :: Code Example of Comparing None with False type 
Python :: tuple with mixed data types 
Python :: how to decide that the input must be a integer less than 5 in python 
Python :: df .isna percentage 
Python :: code academy magic 8 bal code python 
Python :: selenium emojis 
Python :: python 2 pages 
Python :: fetch metric data from aws boto3 
Python :: Python NumPy atleast_3d Function Example 2 
Python :: geopandas nc file 
Python :: Python NumPy asanyarray Function Syntax 
Python :: Python NumPy split Function Example when index attribute given wrong 
Python :: tf idf vectorizer regression -logistic 
Python :: Python how to use __ge__ 
Python :: how to run string like normal code in python 
Python :: WAP to input 3 no.s and print their sum. 
Python :: lambda to redshift python 
Python :: Remove Brackets from List Using the Translate method 
Python :: from android.runnable in python 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =