No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Evaluación resultados de distintos modelos de clustering

25/27
Recursos

Aportes 5

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Hice una visualización en un mapa de los clusters que obtuve haciendo el ejercicio por mi cuenta:
Además, según la distribución de los grupos (Antes de crear el mapa) decidí asignar los siguientes grupos:

No necesita ayuda: cluster 3
Necesidad Baja: clusters 2, 5
Necesidad Media: cluster 0
Necesidad alta: clusters 1, 4

Si relacionamos la imagen con la idea que comúnmente se tiene sobre la situación de distintos países, hay bastantes puntos en común como:

  • Los países anglosajones y Europa occidental con poca necesidad
  • La mayoría de Latinoamérica en necesidad media
  • La mayoría de países africanos en necesidad alta

Con este script pueden obtener un mapa interactivo para visualizar los resultados!!!.

!pip install pycountry

import pycountry
import plotly.express as px

def get_alpha_3(location):
    try:
        return pycountry.countries.get(name=location).alpha_3
    except:
        return None

df_map = df.copy()
df_map['Code'] = df['country'].apply(lambda x: get_alpha_3(x))

fig = px.choropleth(df_map, locations='Code', color='kmeans', hover_name='country', color_continuous_scale=px.colors.sequential.Plasma)
fig.show()
  • Siendo este el resultado:

Solo se deben instalar las librerias que no tenga y ejecutar el codigo al final del notebook en una celda despues de lo escrito por el profesor ya que copia el dataframe del ultimo creado. Si no le queda tan bonito como el mio, busque la plantilla de plotly que deje en las primeras clases de este curso en lla seccion de aportes.

import pycountry
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots


def get_alpha_3(location):
    try:
        return pycountry.countries.get(name=location).alpha_3
    except:
        return None



df_map = df_country.copy()
df_map['iso_alpha'] = df_country['country'].apply(lambda x: get_alpha_3(x))

iso3_to_iso2 = {c.alpha_3: c.alpha_2 for c in pycountry.countries}
df_map["iso_alpha2"] = df_map["iso_alpha"].map(iso3_to_iso2)



# for bar inflation u other
df_bar = df_map[['inflation', 'country', 'k_means_pca']].sort_values(by='inflation',ascending=False).head(10)


# Initialize figure with subplots
fig = make_subplots(
    rows=2, cols=2,
    column_widths=[0.5, 0.5],
    row_heights=[0.6, 0.4],
    subplot_titles=('life expectancy vs inflation with size by gdpp',
                    '10 countries with higher inflation',
                    'Countries of the world by k means pca cluster'),
    specs=[[{"type": "scatter", "colspan": 2}, None],
           [{"type": "bar"}, {"type": "choropleth"}]])


# Add scattergeo globe map of volcano locations
# fig.add_trace(
#     px.choropleth(df_map, locations='Code',
#                   color='k_means_pca',
#                   hover_name='country',
#                   color_continuous_scale=px.colors.sequential.Plasma).data,
#     row=1, col=1
# )


#######################

fig1 = px.scatter(
    df_map,
    x="life_expec",
    y="inflation",
    hover_name="country",
    hover_data=["life_expec", 'inflation', "gdpp"]
)

fig1.update_traces(marker_color="rgba(0,0,0,0)")

minDim = df_map[["life_expec", "inflation"]].max().idxmax()
maxi = df_map[minDim].max()


# fig1.update_layout(height=600, width=1000, plot_bgcolor="#dfdfdf", yaxis_range=[-5e3, 55e3])


trace1 = fig1.data[0]

fig.add_trace(trace1, row=1, col=1)

for i, row in df_map.iterrows():
    country_iso = row["iso_alpha2"]
    fig.add_layout_image(
        dict(
            source=f"https://raw.githubusercontent.com/matahombres/CSS-Country-Flags-Rounded/master/flags/{country_iso}.png",
            xref="x",
            yref="y",
            xanchor="center",
            yanchor="middle",
            x=row["life_expec"],
            y=row["inflation"],
            sizex=np.sqrt(row["gdpp"] / df_map["gdpp"].max()) * maxi * 0.15 + maxi * 0.03,
            sizey=np.sqrt(row["gdpp"] / df_map["gdpp"].max()) * maxi * 0.15+ maxi * 0.03,
            sizing="contain",
            opacity=0.8,
            layer="above"
        )
    )


##########################


# Add locations bar chart
fig.add_trace(
    go.Bar(x=df_bar.country, 
           y=df_bar.inflation,
           marker=dict(color=df_bar.inflation, 
                      showscale=True, 
                      colorscale=px.colors.diverging.RdBu[::-1], 
                      cmax=df_map.inflation.max(), cmin=df_map.inflation.min(),
                      colorbar=dict(len=0.45, x=0.47, y=0.2),
                      colorbar_title = "Inflation",),
           showlegend=False,
          ),
    row=2, col=1
)



fig.add_trace(
    go.Choropleth(
        locations=df_map.iso_alpha,
        z=df_map.k_means_pca,
        marker_line_color='red',
        colorbar_title = "Cluster",
        colorscale=[[0, 'rgb(175, 100, 88)'], [0.25, 'rgb(175, 100, 88)'],
                   [0.25, '#479B55'], [0.5, '#479B55'],
                   [0.5, '#FA0087'], [0.75, '#FA0087'],
                   [0.75, 'rgb(117, 112, 179)'], [1, 'rgb(117, 112, 179)']],
        marker_opacity=0.5, 
        marker_line_width=0,
        hoverinfo='location+z', 
        zmin=df_map.k_means_pca.min(),
        zmax=df_map.k_means_pca.max(),
        colorbar=dict(len=0.45, y=0.2),
    ),
    row=2, col=2
)



#############################################



##################################

# # Add 3d surface of volcano
# fig.add_trace(
#     go.Surface(z=df_v.values.tolist(), showscale=False),
#     row=2, col=2
# )



# Update geo subplot properties
fig.update_geos(
    countrycolor="red",
    fitbounds="locations",
    visible=False,
    projection_type="natural earth",
    landcolor="white",
#     oceancolor="MidnightBlue",
    showocean=True,
#     lakecolor="LightBlue",
    lataxis_showgrid=True, lonaxis_showgrid=True
)

# Rotate x-axis labels
fig.update_xaxes(tickangle=30, automargin='height')

# Set theme, margin, and annotation in layout
fig.update_layout(
    width=1400, height=800,
    margin=dict(r=5, t=25, b=20, l=60),
#     annotations=[
#         dict(
#             text="Source: AAZG",
#             showarrow=False,
#             xref="paper",
#             yref="paper",
#             x=0,
#             y=-0.1)
#     ]
)

# Update xaxis properties
fig.update_xaxes(title_text="Life expectative", row=1, col=1)
fig.update_xaxes(title_text="Paises", row=2, col=1)
# fig.update_xaxes(title_text="xaxis 4 title", type="log", row=2, col=2)

# Update yaxis properties
fig.update_yaxes(title_text="Inflation", row=1, col=1)
fig.update_yaxes(title_text="Inflation", row=2, col=1)
# fig.update_yaxes(title_text="yaxis 4 title", row=2, col=2)

fig.show()

Yo probé con un PCA de 5 y tampoco obtuve diferencias muy significativas…

![](<E:\Angel_M\Cursos Adicionales\Platzi\ML\notebooks\boxplot.png>)