<jupyter_start><jupyter_text>Financial Inclusion remains one of the main obstacles to economic and human development in Africa. For example, across Kenya, Rwanda, Tanzania, and Uganda only 9.1 million adults (or 13.9% of the adult population) have access to or use a commercial bank account.Traditionally, access to bank accounts has been regarded as an indicator of financial inclusion. Despite the proliferation of mobile money in Africa and the growth of innovative fintech solutions, banks still play a pivotal role in facilitating access to financial services. Access to bank accounts enables households to save and facilitate payments while also helping businesses build up their credit-worthiness and improve their access to other financial services. Therefore, access to bank accounts is an essential contributor to long-term economic growth.The research problem is to figure out how we can predict which individuals are most likely to have or use a bank account. Your solution will help provide an indication of the state of financial inclusion in Kenya, Rwanda, Tanzania, and Uganda, while providing insights into some of the key demographic factors that might drive individuals’ financial outcomes. **DEFINING THE QUESTION**figure out how  we can predict which indvidual is most likely to have or  use a bank account **DEFINE METRIC** **FOR**  **SUCCESS** 1) Identify the age group with the most bank accounts.2) Identify household size with the most bank accounts.3) Identify which gender has the most number of bank accounts in different countries.4) Identify which country has the most number of bank accounts as compared to those with the least.5) Corelate individual countries to Levels of education.6) Corelate Levels of Education corelate with people who have bank accounts.7) Corelate Access to Cell Phones with people who have bank accounts. **CONTEXT** **EXPERIMENTAL DESIGN TAKEN** **APPROPRIATENESS OF THE AVAILABLE DATA**<jupyter_code>#importing the required libraries.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

#loading and previewing our variable dataset
variables = pd.read_csv('/content/VariableDefinitions.csv')
variables
#loading and previewing of financial dataset
df=pd.read_csv('/content/Financial Dataset - 1.csv')
df.head(10)
#previewing our tail in our financial dataset
df.tail(10)<jupyter_output><empty_output><jupyter_text>Understanding our data for analysis<jupyter_code>df.info()
df.describe(include='all')
df.describe()<jupyter_output><empty_output><jupyter_text>From our data,the total number of respondents in this dataset is 23490the mean of the age respondent is 38, the standard deviation is 16.the youngest respondent is aged 16 while the oldest is age 100<jupyter_code>df.shape
df.count()
# count the number of people who have a bank account.
#NO means the respondent has no bank account.
#Yes means the respondents has a bank account
df['Has a Bank account'].value_counts()<jupyter_output><empty_output><jupyter_text>Seperate the dataset to two dataframes, one with bank account and the other without.<jupyter_code>df_yes= df[df['Has a Bank account']=='Yes']
df_yes.head()
# dataset with respondents that have bank account
df_no=df[df['Has a Bank account']=='No']
df_no.head()<jupyter_output><empty_output><jupyter_text>in the dataset, NO = 20179 respondents means they do not have a bank account,Yes = 3309 respondents have a bank account. DATA CLEANING.<jupyter_code>#checking for outliers
df['year'].unique()
#Household_size
sns.boxplot(df['household_size'], showmeans=True)


#Respondent age
sns.boxplot(df['Respondent Age'], showmeans=True)
#checking for anomalies
print(df.nunique())
# Checking for anomalies
q1_age = df['Respondent Age'].quantile(.25)
q3_age = df['Respondent Age'].quantile(.75)
iqr_age = q3_age - q1_age

q1_size = df['household_size'].quantile(.25)
q3_size = df['household_size'].quantile(.75)
iqr_size = q3_size - q1_size

q1_year =df['year'].quantile(.25)
q3_year = df['year'].quantile(.75)
iqr_year = q3_year - q1_year

print(iqr_age,iqr_size,iqr_year)
#check for null values in our dataset
df.isnull().sum()
#dropping null values in our dataset
df.dropna(inplace=True)
df.isnull().sum()<jupyter_output><empty_output><jupyter_text>UNIVARIATE ANALYSIS<jupyter_code>#comparing the gender
df_yes['gender_of_respondent'].value_counts().plot.bar(title='male vs female who have bank accounts', color='pink')<jupyter_output><empty_output><jupyter_text>From our graph above, more males have bank account compared to the number of females.<jupyter_code>df_no['gender_of_respondent'].value_counts().plot.bar(title='male vs female who have no bank account', color='blue')
#looking for the house_size with the most bank account
sns.FacetGrid(df_yes, height =6).map(sns.distplot,"household_size").add_legend()
#the age group with the most bank accounts.
sns.FacetGrid(df_yes, height =5).map(sns.distplot,"Respondent Age",color='red').add_legend()
# the age group that has no bank accounts.
sns.FacetGrid(df_no, height =5).map(sns.distplot,"Respondent Age",color='blue').add_legend()<jupyter_output><empty_output><jupyter_text>from the graph above, age group 30 t0 40 are the ones that have most bank accounts  BIVARIATE ANALYSIS<jupyter_code>#the correlation 
df.corr()
# Correlation
plt.figure(dpi = 120,figsize= (5,4))
mask = np.triu(np.ones_like(df.corr(),dtype = bool))
sns.heatmap(df.corr(),mask = mask, fmt = ".2f",annot=True,lw=1,cmap = 'plasma')
plt.yticks(rotation = 0)
plt.xticks(rotation = 90)
plt.title('Correlation Heatmap')
plt.show()<jupyter_output><empty_output><jupyter_text>the respondent ageis weakly correlated to year and the house which is -0.119709<jupyter_code>#Male vs female access to cellphones
#sns.countplot('gender_of_respondent', hue='Cell Phone Access', data=df)
ax = sns.countplot('Cell Phone Access', hue='gender_of_respondent', data=df)
ax.set(ylabel = 'Number of Respondents',
       title = 'Cell Phone Access by Gender')<jupyter_output><empty_output><jupyter_text>from  chart above, more females have access to cellphones compared to men<jupyter_code>#Male vs female level of education
ax = sns.countplot('gender_of_respondent', hue='Level of Educuation', data=df)
ax.set(ylabel = 'Number of Respondents',
       title = 'Education levels by Gender')<jupyter_output><empty_output><jupyter_text>from the graph above, females have a high number in almost each level of education.females also have the nost number with no formal education<jupyter_code>#Cellphone access across different employment types

ax = sns.countplot('Cell Phone Access', hue='Type of Job', data=df)
ax.set(ylabel = 'Number of Respondents',
       title = 'Cellphone access across different employment types')<jupyter_output><empty_output><jupyter_text>from the above graph, the self employed and those doing farming and fishing have cell phone access. most of the self employed too have no cell phone access.<jupyter_code>#check the country with the level of education
sns.set(style="darkgrid")
ax = sns.countplot(x='country', hue= "Level of Educuation", data=df)
plt.show()<jupyter_output><empty_output><jupyter_text>from above, the level of education in uganda is the lowest compared to the other countries,kenya has the highest tertiary education.<jupyter_code># How do the various Levels of Education corelate with people who have bank accounts?
sns.set(style="darkgrid")
ax = sns.countplot(x='Has a Bank account', hue= "Level of Educuation", data=df)
plt.show()<jupyter_output><empty_output><jupyter_text>from above graph, people in primary education have the highest  number with no bank accounts.<jupyter_code>sns.set(style="darkgrid")
ax = sns.countplot(x='Type of Location', hue= "Cell Phone Access", data=df)
plt.show()

sns.set(style="darkgrid")
ax = sns.countplot(x='Has a Bank account', hue=  "Type of Location", data=df)
plt.show()

sns.set(style="darkgrid")
ax = sns.countplot(x='Has a Bank account', hue= "Cell Phone Access", data=df)
plt.show()

ax = sns.countplot(x='Has a Bank account', hue= "Type of Location", data=df)
plt.show()<jupyter_output><empty_output><jupyter_text>Multivariate analysis using PCA<jupyter_code>#pair plot
sns.pairplot(df)
plt.show()
sns.pairplot(df, hue= "Respondent Age", size=3)
plt.show()<jupyter_output>/usr/local/lib/python3.6/dist-packages/seaborn/axisgrid.py:2071: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
  warnings.warn(msg, UserWarning)
/usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:283: UserWarning: Data must have variance to compute a kernel density estimate.
  warnings.warn(msg, UserWarning)
/usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:283: UserWarning: Data must have variance to compute a kernel density estimate.
  warnings.warn(msg, UserWarning)
/usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:283: UserWarning: Data must have variance to compute a kernel density estimate.
  warnings.warn(msg, UserWarning)
/usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:283: UserWarning: Data must have variance to compute a kernel density estimate.
  warnings.warn(msg, UserWarning)
/usr/local/lib/python3.6/dist-packages/seaborn/distributions.py:283: UserWarning: Data must have var[...]<jupyter_text>ANALYSIS USING PCA<jupyter_code>#label data that has two outcomes
encode={"Has a Bank account" : {"Yes" : 1, "No": 0},"Type of Location" : {"Rural" : 1, "Urban" : 0},"Cell Phone Access" : {"Yes" : 1, "No" : 0}, "gender_of_respondent" : {"Female" : 1, "Male" : 1}}
df.replace(encode, inplace = True)
df.head()
#dropping unnecessary columns
df.drop(['country','uniqueid','The relathip with head','marital_status','Level of Educuation','Type of Job'],axis = 1, inplace =True)
#defining the variables
X= df.drop('Has a Bank account',1)
y= df['Has a Bank account']
# dividing the  data into training and test sets

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Feature scaling

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
#importing PCA for our analysis
from sklearn.decomposition import PCA

pca = PCA()
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
#finding the explained variance ratio
explained_variance = pca.explained_variance_ratio_
explained_variance
#using the first principal component for analysis
from sklearn.decomposition import PCA

pca = PCA(n_components=1)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
#Training and Making Predictions
# We will use the random forest classifier to evaluate the performance of a PCA-reduced algorithms as shown
# 

from sklearn.ensemble import RandomForestClassifier

classifier = RandomForestClassifier(max_depth=2, random_state=0)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
# evaluating the perfomance

from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

cm = confusion_matrix(y_test, y_pred)
print(cm)
print('Accuracy' + str(accuracy_score(y_test, y_pred)))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10034725313863414, 'fraction_numerical': 0.012198379485353041, 'mean_word_length': 6.34597776324395, 'pattern_counts': {'":': 1, '<': 64, '<?xml version=': 0, '>': 64, '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': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '367343', 'license': 'MIT', 'n_tokens_mistral': 3653, 'n_tokens_neox': 3446, 'n_words': 1161, 'path': 'WEEK2_IP_CORE_.ipynb', 'repo_name': 'jane95924/JANE_WEEK2_CORE', 'size': '11231'}