import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin_min
%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams['figure.figsize'] = (25, 12)
plt.style.use('ggplot')
#Se importan datos de desempleo desde el PC a Colaboratory
from google.colab import files
import io
uploaded = files.upload()
desempleo_dataframe_leido = pd.read_csv(io.BytesIO(uploaded['unemployment.csv']), header=1)
desempleo_dataframe_leido.head()
#Se importan datos de desempleo desde el PC a Colaboratory
from google.colab import files
import io
uploaded = files.upload()
empleo_dataframe_leido = pd.read_csv(io.BytesIO(uploaded['employment.csv']), header=1)
empleo_dataframe_leido.head()
# Borramos unnamed
for i in range(3,29,2):
title = 'Unnamed: '+str(i)
desempleo_dataframe_leido.drop([title],axis=1,inplace=True)
# Borramos paises nulos
desempleo_dataframe = desempleo_dataframe_leido[desempleo_dataframe_leido['Country'].isnull()==False]
desempleo_dataframe.head()
# Borramos unnamed
for i in range(3,29,2):
title = 'Unnamed: '+str(i)
empleo_dataframe_leido.drop([title],axis=1,inplace=True)
# Borramos paises nulos
empleo_dataframe = empleo_dataframe_leido[empleo_dataframe_leido['Country'].isnull()==False]
empleo_dataframe.head()
#celda backup CORRER 1 SOLA VEZ
backupempleo=empleo_dataframe.copy()
backupdesempleo=desempleo_dataframe.copy()
#celda restore CORRER CADA QUE HAYAN ERRORES POR BORRADO:
empleo_dataframe=backupempleo.copy()
desempleo_dataframe=backupdesempleo.copy()
# Celdas vacias
empleo_dataframe[empleo_dataframe['HDI Rank (2018)'].isnull()==True]
# Paises sin datos de empleo
empleo_dataframe[(empleo_dataframe['1991']=='..') & (empleo_dataframe['2000']=='..') & (empleo_dataframe['2018']=='..')]
# Se borran vacios
empleo_dataframe = empleo_dataframe[empleo_dataframe['HDI Rank (2018)'].isnull()==False]
# Se borran paises sin datos
empleo_dataframe = empleo_dataframe[(empleo_dataframe['1991']!='..') & (empleo_dataframe['2000']!='..') & (empleo_dataframe['2018']!='..')]
# Decada 2000 empleo a numerico
empleo_dataframe["1991"] = pd.to_numeric(empleo_dataframe["1991"], downcast="float")
empleo_dataframe["1995"] = pd.to_numeric(empleo_dataframe["1995"], downcast="float")
empleo_dataframe["2000"] = pd.to_numeric(empleo_dataframe["2000"], downcast="float")
empleo_dataframe["2005"] = pd.to_numeric(empleo_dataframe["2005"], downcast="float")
# Decada 2010 empleo a numerico
empleo_dataframe["2010"] = pd.to_numeric(empleo_dataframe["2010"], downcast="float")
empleo_dataframe["2011"] = pd.to_numeric(empleo_dataframe["2011"], downcast="float")
empleo_dataframe["2012"] = pd.to_numeric(empleo_dataframe["2012"], downcast="float")
empleo_dataframe["2013"] = pd.to_numeric(empleo_dataframe["2013"], downcast="float")
# Decada 2018 empleo a numerico
empleo_dataframe["2014"] = pd.to_numeric(empleo_dataframe["2014"], downcast="float")
empleo_dataframe["2015"] = pd.to_numeric(empleo_dataframe["2015"], downcast="float")
empleo_dataframe["2016"] = pd.to_numeric(empleo_dataframe["2016"], downcast="float")
empleo_dataframe["2017"] = pd.to_numeric(empleo_dataframe["2017"], downcast="float")
empleo_dataframe["2018"] = pd.to_numeric(empleo_dataframe["2018"], downcast="float")
empleo_dataframe.describe()
# Se agrupan por promedio
empleo_dataframe['d2000-empleo'] = empleo_dataframe.iloc[:, 2:5].mean(axis=1)
empleo_dataframe['d2010-empleo'] = empleo_dataframe.iloc[:, 5:7].mean(axis=1)
empleo_dataframe['d2018-empleo'] = empleo_dataframe.iloc[:, 7:15].mean(axis=1)
# Se seleccionan las agrupadas
empleo_final = empleo_dataframe.loc[:,['Country','HDI Rank (2018)','d2000-empleo','d2010-empleo','d2018-empleo']]
empleo_final.head()
# Se borran los paises con ranks nulos
desempleo_dataframe = desempleo_dataframe[desempleo_dataframe['HDI Rank (2018)'].isnull()==False]
# Se borran los paises sin ningun dato
desempleo_dataframe = desempleo_dataframe[(desempleo_dataframe['1991']!='..') & (desempleo_dataframe['2000']!='..') & (desempleo_dataframe['2018']!='..')]
# Decada 2000 empleo a numerico
desempleo_dataframe["1991"] = pd.to_numeric(desempleo_dataframe["1991"], downcast="float")
desempleo_dataframe["1995"] = pd.to_numeric(desempleo_dataframe["1995"], downcast="float")
desempleo_dataframe["2000"] = pd.to_numeric(desempleo_dataframe["2000"], downcast="float")
desempleo_dataframe["2005"] = pd.to_numeric(desempleo_dataframe["2005"], downcast="float")
# Decada 2010 empleo a numerico
desempleo_dataframe["2010"] = pd.to_numeric(desempleo_dataframe["2010"], downcast="float")
desempleo_dataframe["2011"] = pd.to_numeric(desempleo_dataframe["2011"], downcast="float")
desempleo_dataframe["2012"] = pd.to_numeric(desempleo_dataframe["2012"], downcast="float")
desempleo_dataframe["2013"] = pd.to_numeric(desempleo_dataframe["2013"], downcast="float")
# Decada 2018 empleo a numerico
desempleo_dataframe["2014"] = pd.to_numeric(desempleo_dataframe["2014"], downcast="float")
desempleo_dataframe["2015"] = pd.to_numeric(desempleo_dataframe["2015"], downcast="float")
desempleo_dataframe["2016"] = pd.to_numeric(desempleo_dataframe["2016"], downcast="float")
desempleo_dataframe["2017"] = pd.to_numeric(desempleo_dataframe["2017"], downcast="float")
desempleo_dataframe["2018"] = pd.to_numeric(desempleo_dataframe["2018"], downcast="float")
# Se agrupan por promedio
desempleo_dataframe['d2000-desempleo'] = desempleo_dataframe.iloc[:, 2:5].mean(axis=1)
desempleo_dataframe['d2010-desempleo'] = desempleo_dataframe.iloc[:, 5:7].mean(axis=1)
desempleo_dataframe['d2018-desempleo'] = desempleo_dataframe.iloc[:, 7:15].mean(axis=1)
# Se seleccionan las agrupadas
desempleo_final = desempleo_dataframe.loc[:,['Country','HDI Rank (2018)','d2000-desempleo','d2010-desempleo','d2018-desempleo']]
desempleo_final.head()
prototipo = pd.merge(empleo_final, desempleo_final, on=['Country','HDI Rank (2018)'])
prototipo
plt.rcParams['figure.figsize'] = (25, 12)
prototipo.hist()
plt.show()
sb.pairplot(prototipo.dropna(), size=4,vars=["d2000-empleo", "d2000-desempleo", "d2018-desempleo"],kind='scatter')
X = prototipo
X_arr = np.array(prototipo[["d2000-empleo", "d2000-desempleo", "d2018-desempleo"]])
X_arr.shape
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X_arr[:, 0], X_arr[:, 1], X_arr[:, 2],s=60)
Nc = range(1, 40)
kmeans = [KMeans(n_clusters=i) for i in Nc]
kmeans
score = [kmeans[i].fit(X_arr).score(X_arr) for i in range(len(kmeans))]
score
plt.plot(Nc,score)
plt.xlabel('Number of Clusters')
plt.ylabel('Score')
plt.title('Elbow Curve')
plt.show()
data = X_arr
nrefs = 1
maxClusters = 10
gaps = np.zeros((len(range(1, maxClusters)),))
resultsdf = pd.DataFrame({'clusterCount': [], 'gap': []})
for gap_index, k in enumerate(range(1, maxClusters)):
refDisps = np.zeros(nrefs) # Holder for reference dispersion results
# For n references, generate random sample and perform kmeans getting resulting dispersion of each loop
for i in range(nrefs):
np.random.seed(0)
randomReference = np.random.random_sample(size=data.shape) # Create new random reference set
km = KMeans(k) # Fit to it
km.fit(randomReference)
refDisp = km.inertia_
refDisps[i] = refDisp
km = KMeans(k) # Fit cluster to original data and create dispersion
km.fit(data)
origDisp = km.inertia_
gap = np.log(np.mean(refDisps)) - np.log(origDisp) # Calculate gap statistic
gaps[gap_index] = gap # Assign this loop's gap statistic to gaps
resultsdf = resultsdf.append({'clusterCount': k, 'gap': gap}, ignore_index=True)
# Plus 1 because index of 0 means 1 cluster is optimal, index 2 = 3 clusters are optimal
k,resultsdf = (gaps.argmax() + 1, resultsdf)
n_clusters = k
print(k)
kmeans = KMeans(n_clusters=5).fit(X_arr)
centroids = kmeans.cluster_centers_
print(centroids)
# Predicting the clusters
labels = kmeans.predict(X_arr)
# Getting the cluster centers
C = kmeans.cluster_centers_
colores=['red','green','blue','cyan','yellow']
asignar=[]
for row in labels:
asignar.append(colores[row])
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X_arr[:, 0], X_arr[:, 1], X_arr[:, 2], c=asignar,s=60)
ax.scatter(C[:, 0], C[:, 1], C[:, 2], marker='*', c=colores, s=1000)
f1 = X["d2000-empleo"].values
f2 = X["d2000-desempleo"].values
plt.scatter(f1, f2, c=asignar, s=70)
plt.scatter(C[:, 0], C[:, 1], marker='*', c=colores, s=1000)
plt.show()
f1 = X["d2000-empleo"].values
f2 = X["d2018-desempleo"].values
plt.scatter(f1, f2, c=asignar, s=70)
plt.scatter(C[:, 0], C[:, 1], marker='*', c=colores, s=1000)
plt.show()
f1 = X["d2000-desempleo"].values
f2 = X["d2018-desempleo"].values
plt.scatter(f1, f2, c=asignar, s=70)
plt.scatter(C[:, 0], C[:, 1], marker='*', c=colores, s=1000)
plt.show()
closest, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, X_arr)
closest
n = 1
for row in closest:
print("\nUsuario mas representativo de cluster: "+str(n)+"\n")
print(prototipo.iloc[row])
n = n+1
# Obtenemos el empleo en latinoamerica por decadas del dataset de empleo
empleo_final[empleo_final['Country']=='Latin America and the Caribbean']
# Obtenemos el desempleo en latinoamerica del dataset backup, ya que el original fue modificado.
A = backupdesempleo[backupdesempleo['Country']=="Latin America and the Caribbean"].copy()
A
# Se aplican las correcciones al dato de latinoamerica para obtener el desempleo por decadas
# Decada 2000 empleo a numerico
A["1995"] = pd.to_numeric(A["1995"], downcast="float")
A["2000"] = pd.to_numeric(A["2000"], downcast="float")
A["2005"] = pd.to_numeric(A["2005"], downcast="float")
# Decada 2010 empleo a numerico
A["2010"] = pd.to_numeric(A["2010"], downcast="float")
A["2011"] = pd.to_numeric(A["2011"], downcast="float")
A["2012"] = pd.to_numeric(A["2012"], downcast="float")
A["2013"] = pd.to_numeric(A["2013"], downcast="float")
# Decada 2018 empleo a numerico
A["2014"] = pd.to_numeric(A["2014"], downcast="float")
A["2015"] = pd.to_numeric(A["2015"], downcast="float")
A["2016"] = pd.to_numeric(A["2016"], downcast="float")
A["2017"] = pd.to_numeric(A["2017"], downcast="float")
A["2018"] = pd.to_numeric(A["2018"], downcast="float")
# Se agrupan por promedio
A['d2000-desempleo'] = A.iloc[:, 3:5].mean(axis=1)
A['d2010-desempleo'] = A.iloc[:, 5:7].mean(axis=1)
A['d2018-desempleo'] = A.iloc[:, 7:15].mean(axis=1)
# Se seleccionan las agrupadas
desempleo_final = A.loc[:,['Country','HDI Rank (2018)','d2000-desempleo','d2010-desempleo','d2018-desempleo']]
desempleo_final.head()
#Colocamos los valores de d2000-empleo,d2000-desempleo y d2018-desempleo de latinoamerica para clasificarlos.
X_new = np.array([[22.0,15.35,15.262499]])
new_labels = kmeans.predict(X_new)
print("Latinoamerica fue clasificado en el cluster: "+str(new_labels[0]+1))
lista = []
paises = ['Colombia', 'France', 'Nigeria', 'Japan', 'New Zealand']
for pais in paises:
a = prototipo[prototipo['Country']==pais].iloc[0]
empleo2000pais=a[2]
desempleo2000pais=a[5]
desempleo2018pais=a[7]
lista.append([empleo2000pais,desempleo2000pais,desempleo2018pais])
Xnew = np.array(lista)
new_labels = kmeans.predict(Xnew)
for i in range(0, len(new_labels)):
print("El pais "+str(paises[i])+" pertenece al cluster "+str((new_labels[i]+1)))
print(prototipo[prototipo['Country']==paises[i]].iloc[0])
print("\n")