File size: 7,073 Bytes
baae561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score


# In[3]:


# Load the datasets 
file_paths = {
    "bank_additional": "bank-additional.xlsx",
    "bank_additional_full": "bank-additional-full.xlsx",
    "bank_full": "bank-full.xlsx",
    "bank": "bank.xlsx"
}


# In[6]:


# Reading the datasets into pandas dataframes
bank_additional = pd.read_excel(file_paths["bank_additional"])


# In[7]:


# Reading the datasets into pandas dataframes
bank_additional_full = pd.read_excel(file_paths["bank_additional_full"])


# In[8]:


# Reading the datasets into pandas dataframes
bank_full = pd.read_excel(file_paths["bank_full"])


# In[9]:


# Reading the datasets into pandas dataframes
bank = pd.read_excel(file_paths["bank"])


# In[10]:


# Displaying the first few rows and basic info for each dataset to understand their structure
datasets_info = {
    "bank_additional": bank_additional.info(),
    "bank_additional_full": bank_additional_full.info(),
    "bank_full": bank_full.info(),
    "bank": bank.info()
}


# In[11]:


bank_additional.head()


# In[12]:


bank_additional_full.head()


# In[13]:


bank_full.head()


# In[14]:


datasets_info


# In[15]:


# Using the bank_additional_full dataset for EDA
data = bank_additional_full.copy()


# In[16]:


# Checking for missing values
missing_values = data.isnull().sum()


# In[18]:


# Basic statistics
basic_stats = data.describe(include="all")


# In[22]:


# Basic statistics
basic_stats = data.describe(include="all")

missing_values, basic_stats


# In[19]:


# 1. Overview of the dataset
print("Dataset shape:", data.shape)


# In[20]:


print("\nDataset sample:\n", data.head())


# In[21]:


print("\nData types:\n", data.dtypes)


# In[22]:


# 2 Summary statistics
print("\nSummary statistics (numerical features):\n", data.describe())


# In[23]:


print("\nSummary statistics (categorical features):\n", data.describe(include=['object']))


# In[25]:


# 3. Correlation analysis (numerical features)
numerical_features = data.select_dtypes(include=['int64', 'float64']).columns
plt.figure(figsize=(10, 8))
sns.heatmap(data[numerical_features].corr(), annot=True, cmap='coolwarm', fmt=".2f")
plt.title('Correlation Matrix (Numerical Features)')
plt.show()


# In[26]:


# 4 Distribution of key numerical features
for col in numerical_features:
    plt.figure(figsize=(6, 4))
    sns.histplot(data[col], kde=True, bins=30)
    plt.title(f'Distribution of {col}')
    plt.xlabel(col)
    plt.ylabel('Frequency')
    plt.show()


# In[27]:


# 5 Boxplot to identify outliers
for col in numerical_features:
    plt.figure(figsize=(6, 4))
    sns.boxplot(data[col])
    plt.title(f'Boxplot of {col}')
    plt.xlabel(col)
    plt.show()


# In[28]:


# 6 Relationship between key features and target
categorical_features = data.select_dtypes(include=['object']).columns

for col in categorical_features:
    plt.figure(figsize=(10, 6))
    sns.countplot(x=col, hue='y', data=data)
    plt.title(f'{col} vs Subscription (y)')
    plt.xlabel(col)
    plt.ylabel('Count')
    plt.legend(title='Subscription', loc='upper right')
    plt.xticks(rotation=45)
    plt.show()


# In[15]:


# 7 Visualizing target variable distribution
plt.figure(figsize=(8, 6))
sns.countplot(data=data, x='y', palette='coolwarm')
plt.title("Subscription Outcome Distribution (y)", fontsize=14)
plt.xlabel("Subscription ('yes' or 'no')")
plt.ylabel("Count")
plt.show()


# In[16]:


# 7 Correlation heatmap for numerical features
plt.figure(figsize=(10, 8))
numerical_cols = data.select_dtypes(include=['float64', 'int64']).columns
correlation_matrix = data[numerical_cols].corr()
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")
plt.title("Correlation Heatmap for Numerical Features", fontsize=14)
plt.show()


# Summary of Findings from EDA:
# Data Integrity:
# 
# There are no missing values across all features in the dataset.
# The target variable y (subscription) is imbalanced, with significantly more "no" than "yes" responses. Addressing this imbalance will be critical during model training.
# Numerical Feature Correlations:
# 
# Features like euribor3m (3-month Euribor rate) and nr.employed (number of employees) exhibit strong correlations with other numerical variables, indicating potential predictive power.
# Key Statistics:
# 
# Age ranges from 17 to 98, with a mean of ~40.
# Features such as pdays and previous show many default values (e.g., 999 for pdays), likely needing special handling.
# Next Steps:
# Data Preprocessing:
# 
# Handle imbalanced classes using oversampling (e.g., SMOTE) or class weighting.
# Normalize numerical features for algorithms sensitive to feature scales.
# Encode categorical variables using techniques like one-hot encoding or label encoding.
# Feature Engineering:
# 
# Evaluate feature importance.
# Consider interactions or derived metrics from existing features.
# Predictive Modeling:
# 
# Train models like Logistic Regression, Random Forest, or Gradient Boosting.
# Use cross-validation to assess model performance using metrics such as F1 score due to the class imbalance.

# In[30]:


# Encode categorical features
categorical_columns = data.select_dtypes(include=['object']).columns
label_encoders = {}
for col in categorical_columns:
    le = LabelEncoder()
    data[col] = le.fit_transform(data[col])
    label_encoders[col] = le


# In[31]:


# Split the data into features and target
X = data.drop('y', axis=1)  # Assuming 'y' is the target column
y = data['y']

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)


# In[32]:


# Apply SMOTE to handle class imbalance
smote = SMOTE(random_state=42)
X_train_balanced, y_train_balanced = smote.fit_resample(X_train, y_train)

# Scale numerical features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train_balanced)
X_test_scaled = scaler.transform(X_test)


# In[33]:


# Train a Logistic Regression model
model = LogisticRegression(random_state=42)
model.fit(X_train_scaled, y_train_balanced)


# In[34]:


# Make predictions
y_pred = model.predict(X_test_scaled)


# In[35]:


# Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))


# Insights and Next Steps:
# 
# Feature Importance: Logistic regression provides coefficients that indicate feature importance. Features with higher absolute coefficients contribute more to the prediction.
# 
# Evaluation Metrics: The classification report provides accuracy, precision, recall, and F1 scores.

# In[ ]:





# In[ ]: