You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
1 Hrs
22 Min
53 Seg

Análisis exploratorio y escalamiento de datos multiclase

14/17
Resources

Why is it important to perform an exploratory data analysis?

Exploratory data analysis is crucial to identify relevant patterns and possible correlations between variables in a dataset. This not only helps to improve the understanding of the data, but also optimizes the performance of predictive models by identifying and eliminating variables that could induce noise or collinearity in the data.

How do we analyze the correlation between variables?

In this lesson, a correlation analysis was performed by visualizing a heatmap of the correlations between attributes in the dataset. In this context, correlations can vary between -1 and 1:

  • 1 or close to 1: Highly correlated.
  • 0 or close to 0: Not correlated.
  • -1 or close to -1: Inverse correlation.

The objective is to discover highly correlated variables that could affect the model and decide whether to eliminate them.

Correlation analysis code example:

plt.figure(figsize=(15, 10))sns.heatmap(dtf.corr(), annot=True)plt.show().

Which variables did we eliminate and why?

From the analysis, it was decided to eliminate the variables convex_area and equidiameter due to their high correlation with other variables such as area, perimeter, length, and width, which could lead to overfitting of the model.

Example code for dropping variables:

xOver.drop(['convex_area', 'equidiameter'], axis=1, inplace=True).

How do we visualize the distribution of our variables and classes?

Visualization is a powerful tool in exploratory analysis. By creating scatter plots and Kernel Density Estimation (KDE), we can assess whether classes within the data are linearly separable. This makes it easier to understand the structure of the data and the selection of the classification method.

Example code for visualization:

sns.pairplot(df,  hue="class").

Why perform scaling and splitting of the dataset?

Scaling the data and then splitting it into training and test sets are fundamental steps to standardize the data, ensure that the model obtains replicable results, and generalizes correctly to new data that it has not seen.

Example code for scaling and splitting:

X_train, X_test, y_train, y_test = train_test_split(XOver, YOver,  test_size=0.2, random_state=42, shuffle=True)
scaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)

Practical conclusions

By applying these steps, not only the quality of the dataset is improved, but also the knowledge about the business and the data on which the model is based is strengthened. This knowledge allows you to fine-tune decisions throughout the modeling process for more accurate and efficient predictions. Ready to keep learning? Let's move on to the next module to continue improving our data science skills!

Contributions 8

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

En el segundo 00:52 se está cometiendo un ERROR, el cual es muy sutil pero genera problemas de sobre-confianza al entrenar el modelo,dado que en la parte final del curso se obtiene un modelo con 0.99 de accuracy cuando en realidad es de solo 0.93, el error que se comete es el siguiente:
Al realizar

df_dea = X_over
df_dea[‘Class’] = y_over

Le estamos asignando una columna extra a la data X_over la cual es la columna de las clases,en el minuto 05:17 se observa que se eliminan 2 columnas,sin embargo, no se elimina la columna Classes la cual queda adherida al DataFrame X_over tal como se observa aquí:

Por lo que al tener esta columna dentro de los features de entrenamiento es muy FACIL para el modelo establecer los patrones y generar un modelo con tan buen accuracy tal como se puede observar en la siguiente clase

En todo caso ,si lo que se quería era generar un nuevo dataset para usar heatmap y ver las correlaciones ,simplemente se pudo usar la función concat de pandas ( en la cual uno el nuevo set de X & y generados con la librería imblearn ) tal como se muestra a continuación
:

Siempre me ha parecido más intuitivo usar la paleta coolwarm para las matrices de correlación

df_under=X_under
df_under['Class']=y_under
plt.figure(figsize=(15,10))
sns.heatmap(df_under.corr(), annot= True, cmap='coolwarm',cbar=False);
Quiero hacer una observación importante en el minuto 9:20 sobre porque en el `x_train` se usa `fit_transform()` y porque en el `x_test` se usa solo `transform()`. Cuando se hace `fit()` con los datos del set para training, internamente se calculan medias y desviaciones estándar para cada una de las columnas del dataset, ya que cada columna tiene diferentes medias y desviaciones estándar. Solo se calcula para el training set porque es el set mas grande, por lo tanto mas representativo de datos para cada columna (80% de los datos van en el `x_train` ). Si se calcularan por separado, es decir, si se hiciera `fit_transform` para el `x_test` por separado, se corre el riesgo que la media y la desviación estándar calculadas difieran, y por lo tanto, al hacer pruebas no se podría evaluar correctamente el performance del modelo.
Cambié un poquito lo que fue el *heatmap*: ```python plt.figure(figsize=(15, 10)) sns.heatmap(data_EDA.corr(), annot=True, cmap='coolwarm') plt.show() ``` ![](https://static.platzi.com/media/user_upload/image-dbb11f55-2168-4220-b824-e2f9585fae43.jpg)

Como no sabemos cuáles son las unidades de los datos, si se hace una correlación sin que todos estos estén en una escala estándar, esto nos conduciría a conclusiones erróneas.

¿No se debería hacer el escalamiento antes de realizar el análisis de correlación? O ¿El método de correlación de Pandas realiza la estandarización internamente?

En caso de que quieran que los valores de correlación que están por encima de la diagonal de la matriz no aparezcan, pueden usar el siguiente código: ```python corr = df_dea.corr() mask = np.triu(np.ones_like(corr)) sns.heatmap(corr,annot=True,mask=mask) ```

Prefiero usar:

%%time

pio.templates['new_template']['layout']['font'] = {'family': 'verdana', 'size': 7, 'color': 'white'}


fig = px.scatter_matrix(
    df_under,
    color="Class",
    title="Scatter matrix of dataset",
    labels={col: col.replace("_", " ") for col in df.columns},
    opacity=0.8, width=1600, height=1600, color_continuous_scale=px.colors.sequential.Magenta
)

fig.update_traces(diagonal_visible=False)
fig.update_coloraxes(showscale=False)
fig.update_traces(marker=dict(size=4, line=dict(width=1, color=px.colors.sequential.Magenta)))

fig.show()

La diferencia de tiempo de ejecucion con respecto a sns.pairplot(df_under, hue=‘Class’) es exageradamente notable.

Una clase compleja para mí. Per sé que con práctica lograré dominar estos conceptos 😎