<jupyter_start><jupyter_text>Regressão logística Determinar se um usuário comprou uma SUV baseado em sua idade e estimativa salarial Dataset obtido no Kaggle (https://www.kaggle.com/hamzaalijoiyah/users-of-a-social-networks-who-bought-suv)<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
dados = pd.read_csv('Social_Network_Ads.csv')
dados.head()
sns.scatterplot(x='Age',y='EstimatedSalary',data=dados,hue='Purchased')
plt.xlabel('Idade')
plt.ylabel('Salário')
plt.tight_layout()<jupyter_output><empty_output><jupyter_text>A coluna ID do usuário não é relevante e será removida<jupyter_code>dados = dados.drop('User ID',axis=1)
dados.head()<jupyter_output><empty_output><jupyter_text>Informações iniciais da amostra<jupyter_code>dados.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 400 entries, 0 to 399
Data columns (total 4 columns):
 #   Column           Non-Null Count  Dtype 
---  ------           --------------  ----- 
 0   Gender           400 non-null    object
 1   Age              400 non-null    int64 
 2   EstimatedSalary  400 non-null    int64 
 3   Purchased        400 non-null    int64 
dtypes: int64(3), object(1)
memory usage: 12.6+ KB<jupyter_text>Verificando a existência de NaNs<jupyter_code>dados.isna().sum()<jupyter_output><empty_output><jupyter_text>Determinando número de clientes homens ou mulher<jupyter_code>sns.countplot(x='Gender',data=dados)<jupyter_output><empty_output><jupyter_text>Verificando distribuição das idades<jupyter_code>sns.distplot(dados['Age'])<jupyter_output><empty_output><jupyter_text>Verificando distribuição da renda<jupyter_code>sns.distplot(dados['EstimatedSalary'])<jupyter_output><empty_output><jupyter_text>Verificando quantidade de clientes quem compraram ou não SUV<jupyter_code>sns.countplot(x='Purchased',data=dados)<jupyter_output><empty_output><jupyter_text>A coluna genero (Gender) precisa ser transformada de variável categórica para variável numérica<jupyter_code>from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit(dados['Gender'])
list(le.classes_)
dados['Gender'] = le.transform(dados['Gender'])
dados.head()<jupyter_output><empty_output><jupyter_text>Normalizando os dados dos salários<jupyter_code>from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
dados[['Age','EstimatedSalary']] = sc_X.fit_transform(dados[['Age','EstimatedSalary']])
dados.head()<jupyter_output><empty_output><jupyter_text>Separando as variáveis X e Y<jupyter_code>X = dados.drop('Purchased',axis=1).values
Y = dados['Purchased'].values<jupyter_output><empty_output><jupyter_text>Separando dados em amostras de treino e teste<jupyter_code>from sklearn.model_selection import train_test_split
X_treino,X_teste,Y_treino,Y_teste=train_test_split(X,Y,test_size=0.25,random_state=0)<jupyter_output><empty_output><jupyter_text>Aplicando modelo de regressão logística<jupyter_code>from sklearn.linear_model import LogisticRegression
modelo = LogisticRegression()
modelo.fit(X_treino,Y_treino)<jupyter_output><empty_output><jupyter_text>Realizando previsão na amostra de teste<jupyter_code>Y_previsto = modelo.predict(X_teste)<jupyter_output><empty_output><jupyter_text>Determinando a matriz de confusão para verificar eficácio do modelo<jupyter_code>from sklearn.metrics import confusion_matrix
cm=confusion_matrix(Y_teste,Y_previsto)
cm
sns.heatmap(cm,annot=True, fmt="d")<jupyter_output><empty_output><jupyter_text>Calculando as métricas do modelo<jupyter_code>from sklearn.metrics import classification_report,f1_score,precision_score,average_precision_score,recall_score,accuracy_score<jupyter_output><empty_output><jupyter_text>Relatório de classificação<jupyter_code>cr = classification_report(Y_teste,Y_previsto,labels=[0,1])
print(cr)<jupyter_output>precision    recall  f1-score   support

           0       0.90      0.96      0.93        68
           1       0.89      0.78      0.83        32

    accuracy                           0.90       100
   macro avg       0.90      0.87      0.88       100
weighted avg       0.90      0.90      0.90       100<jupyter_text>F1-score<jupyter_code>f1 = f1_score(Y_teste,Y_previsto)
print("F1 score = {:0.2f}%".format(f1*100))<jupyter_output>F1 score = 83.33%<jupyter_text>Precision score<jupyter_code>precisao = precision_score(Y_teste,Y_previsto)
print("Precision score = {:0.2f}%".format(precisao*100))<jupyter_output>Precision score = 89.29%<jupyter_text>Average precision score<jupyter_code>avg_precision = average_precision_score(Y_teste,Y_previsto)
print("Averaged Precision score = {:0.2f}%".format(avg_precision*100))<jupyter_output>Averaged Precision score = 76.75%<jupyter_text>Recall score<jupyter_code>rec = recall_score(Y_teste,Y_previsto)
print("Recall score = {:0.2f}%".format(rec*100))<jupyter_output>Recall score = 78.12%<jupyter_text>Accuracy score<jupyter_code>acc = accuracy_score(Y_teste,Y_previsto)
print("Accuracy score = {:0.2f}%".format(acc*100))<jupyter_output>Accuracy score = 90.00%<jupyter_text>Curva ROC<jupyter_code>from sklearn.metrics import roc_curve, roc_auc_score
roc_score = roc_auc_score(Y_teste, Y_previsto)
print("ROC score = {:0.2f}%".format(roc_score*100))
roc_fpr, roc_tpr, _ = roc_curve(Y_teste, Y_previsto)
plt.plot(roc_fpr, roc_tpr, linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')<jupyter_output><empty_output><jupyter_text>Curva Precision-Recall<jupyter_code>from sklearn.metrics import precision_recall_curve,auc
lr_precision, lr_recall, _ = precision_recall_curve(Y_teste, Y_previsto)
lr_auc = auc(lr_recall, lr_precision)
print("AUC score = {:0.2f}%".format(lr_auc*100))
plt.plot(lr_recall, lr_precision)
plt.xlabel('Recall')
plt.ylabel('Precision')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11739280774550484, 'fraction_numerical': 0.028008298755186723, 'mean_word_length': 6.796495956873315, 'pattern_counts': {'":': 0, '<': 91, '<?xml version=': 0, '>': 91, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '24', 'dir': 'jupyter-structured-clean-dedup', 'id': '213371', 'license': 'MIT', 'n_tokens_mistral': 2359, 'n_tokens_neox': 2190, 'n_words': 328, 'path': 'Data_Science/Classificacao/Regressao_Logistica/Regressao_Logistica_SUV.ipynb', 'repo_name': 'maledicente/cursos', 'size': '5784'}