<jupyter_start><jupyter_text>Imbalanced Data<jupyter_code>import pandas as pd 
import numpy as np 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.model_selection import train_test_split 
from sklearn.metrics import classification_report,\
                            confusion_matrix,\
                            accuracy_score 
from sklearn import metrics 
import matplotlib.pyplot as plt 
import seaborn as sns
data =  pd.read_csv('adult.csv')
data.head()
data.replace('?',np.nan,inplace=True)
#Dropping all NULL values
data.dropna(inplace=True)
data['income'].value_counts()
#Encoding the Categorical values to Numericals using LabelEncoder 
from sklearn.preprocessing import LabelEncoder 

Labelenc_workclass = LabelEncoder() 
data['workclass'] = Labelenc_workclass\
            .fit_transform(data['workclass'])

Labelenc_education = LabelEncoder() 
data['education'] = Labelenc_education\
            .fit_transform(data['education'])

Labelenc_marital_status = LabelEncoder() 
data['marital-status'] = Labelenc_marital_status\
            .fit_transform(data['marital-status']) 

Labelenc_occupation = LabelEncoder() 
data['occupation'] = Labelenc_occupation\
            .fit_transform(data['occupation']) 

Labelenc_relationship = LabelEncoder() 
data['relationship'] = Labelenc_relationship\
            .fit_transform(data['relationship']) 

Labelenc_race = LabelEncoder() 
data['race'] = Labelenc_race\
        .fit_transform(data['race']) 

Labelenc_gender = LabelEncoder() 
data['gender'] = Labelenc_gender\
        .fit_transform(data['gender']) 

Labelenc_native_country = LabelEncoder() 
data['native-country'] = Labelenc_native_country\
            .fit_transform(data['native-country']) 

Labelenc_income = LabelEncoder() 
data['income'] = Labelenc_income\
        .fit_transform(data['income']) 
data.head()
# Putting feature variable to X
X = data.drop(['income'],axis=1)
# Putting response variable to y
y = data['income']
X_train, X_test, y_train, y_test = train_test_split\
                    (X,y,\
                    test_size=0.20, \
                    random_state=123) 
clf_random = RandomForestClassifier(random_state=0)
clf_random.fit(X_train,y_train)
y_pred=clf_random.predict(X_test)
print(classification_report(y_test, y_pred))
cm = confusion_matrix(y_test, y_pred)  

cm_df = pd.DataFrame(cm,\
            index = ['<=50K', '>50K'], \
            columns = ['<=50K', '>50K']) 
plt.figure(figsize=(8,6))
sns.heatmap(cm_df, annot=True,fmt='g',cmap='Greys_r')
plt.title('Random Forest \nAccuracy:{0:.3f}'\
    .format(accuracy_score(y_test, y_pred)))
plt.ylabel('True Values')
plt.xlabel('Predicted Values')
plt.show()<jupyter_output><empty_output><jupyter_text>Exercise 9.04  Fitting a Random Forest Classifier using SMOTE and Building the Confusion Matrix<jupyter_code>import imblearn 
from imblearn.over_sampling import SMOTE 
X_resampled, y_resampled = SMOTE().fit_resample(X_train,y_train)
clf_random.fit(X_resampled,y_resampled)
y_pred=clf_random.predict(X_test)
print(classification_report(y_test, y_pred))
cm = confusion_matrix(y_test, y_pred)  

cm_df = pd.DataFrame(cm,\
            index = ['<=50K', '>50K'], \
            columns = ['<=50K', '>50K']) 
plt.figure(figsize=(8,6))
sns.heatmap(cm_df, annot=True,fmt='g',cmap='Greys_r')
plt.title('Random Forest \nAccuracy:{0:.3f}'\
    .format(accuracy_score(y_test, y_pred)))
plt.ylabel('True Values')
plt.xlabel('Predicted Values')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12991109836535705, 'fraction_numerical': 0.010037281330656725, 'mean_word_length': 4.527733755942948, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '508858', 'license': 'MIT', 'n_tokens_mistral': 1240, 'n_tokens_neox': 1169, 'n_words': 204, 'path': 'Chapter09/Exercise9.04/Exercise9.04.ipynb', 'repo_name': 'abhishekr128/Data-Science-for-Marketing-Analytics-Second-Edition', 'size': '3487'}