Dovdush_KN-305_lab3
Dovdush_KN-305_lab3
Довбуш Павло
In [1]: !pip install numpy
!pip install matplotlib
!pip install pandas
!pip install seaborn
!pip install tabulate
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
True
In [6]: ds = pd.read_csv("dataset_3.csv")
ds.head()
Out[6]: Unnamed: 0 Age Sex ChestPainType RestingBP Cholesterol FastingBS RestingECG MaxHR ExerciseAngina Oldpeak ST_Slope HeartDisease
1 1 49.0 F NAP NaN 180.0 NaN Normal 156.0 N 1.0 Flat 1.0
3 3 48.0 F ASY 138.0 214.0 0.0 Normal 108.0 Y 1.5 Flat 1.0
columns count - 13
columns: ['Unnamed: 0', 'Age', 'Sex', 'ChestPainType', 'RestingBP', 'Cholesterol', 'FastingBS', 'RestingECG', 'MaxHR', 'ExerciseAngina', 'Oldpeak', 'ST_Slope', 'HeartDisease']
In [9]: ds.dtypes
return df[variable].fillna(value)
Categorical encoding
In [15]: ds.nunique()
In [16]: ds['Sex'].unique()
In [17]: ds['ChestPainType'].unique()
In [18]: ds['RestingECG'].unique()
In [19]: ds['ExerciseAngina'].unique()
In [20]: ds['ST_Slope'].unique()
In [23]: ds.head(10)
Out[23]: Unnamed: 0 Age Sex ChestPainType RestingBP Cholesterol FastingBS RestingECG MaxHR ExerciseAngina Oldpeak ST_Slope HeartDisease
# histogram
plt.subplot(1, 3, 1)
sns.histplot(df[variable], bins=30)
plt.title('Histogram')
# Q-Q plot
plt.subplot(1, 3, 2)
stats.probplot(df[variable], dist="norm", plot=plt)
plt.ylabel('Variable quantiles')
# boxplot
plt.subplot(1, 3, 3)
sns.boxplot(y=df[variable])
plt.title('Boxplot')
plt.show()
Data Scaling
In [31]: from sklearn.preprocessing import MinMaxScaler,StandardScaler
mms = MinMaxScaler() # Normalization
ss = StandardScaler() # Standardization
ds['Oldpeak'] = mms.fit_transform(ds[['Oldpeak']])
ds['Age'] = ss.fit_transform(ds[['Age']])
ds['RestingBP'] = ss.fit_transform(ds[['RestingBP']])
ds['Cholesterol'] = ss.fit_transform(ds[['Cholesterol']])
ds['MaxHR'] = ss.fit_transform(ds[['MaxHR']])
ds.head()
Out[31]: Unnamed: 0 Age Sex ChestPainType RestingBP Cholesterol FastingBS RestingECG MaxHR ExerciseAngina Oldpeak ST_Slope HeartDisease
Модель машинного навчання не розуміє одиниці значень ознак. Він розглядає вхідні дані як просте число, але не розуміє справжнього значення цього значення. Таким чином, виникає необхідність масштабувати дані.
У нас є 2 варіанти масштабування даних: 1) Нормалізація 2) Стандартизація. Оскільки більшість алгоритмів передбачає, що дані мають нормальний (гаусівський) розподіл, нормалізація виконується для функцій, дані яких не відображають нормального розподілу, а
стандартизація виконується для функцій, які нормально розподіляються, де їхні значення величезні або дуже малі порівняно з іншими особливості.
Нормалізація: функцію Oldpeak нормалізовано, оскільки вона відображала правий спотворений розподіл даних. Стандартизація: Age, RestingBP, Cholesterol і MaxHR зменшено, оскільки ці функції розподілені нормально.
Modeling
In [32]: from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier, ExtraTreesClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from lightgbm import LGBMClassifier
from sklearn.neural_network import MLPClassifier
Out[33]: Unnamed: 0 Age Sex ChestPainType RestingBP Cholesterol FastingBS RestingECG MaxHR ExerciseAngina Oldpeak ST_Slope
... ... ... ... ... ... ... ... ... ... ... ... ...
In [35]: models = [
{
"name": "Logistic Regression",
"estimator": LogisticRegression(),
"hyperparameters": {
"penalty": ["l2"],
"C": [0.01, 0.1, 1, 10],
"max_iter": [500]
}
},
{
"name": "Gradient Boosting",
"estimator": GradientBoostingClassifier(),
"hyperparameters": {
"n_estimators": [100],
"learning_rate": [0.1],
"max_depth": [3]
}
},
{
"name": "Random Forest",
"estimator": RandomForestClassifier(),
"hyperparameters": {
"n_estimators": [100, 200, 300],
"max_depth": [3, 5, 10],
"min_samples_split": [2, 5, 10],
"min_samples_leaf": [1, 2, 4]
}
},
{
"name": "Decision Tree",
"estimator": DecisionTreeClassifier(),
"hyperparameters": {
"criterion": ["gini", "entropy"],
"max_depth": [3, 5, 10],
"min_samples_split": [2, 5, 10],
"min_samples_leaf": [1, 2, 4]
}
},
{
"name": "K-Nearest Neighbors",
"estimator": KNeighborsClassifier(),
"hyperparameters": {
"n_neighbors": [3, 5, 7],
"weights": ["uniform", "distance"],
"algorithm": ["auto", "ball_tree", "kd_tree", "brute"]
}
},
{
"name": "Naive Bayes",
"estimator": GaussianNB(),
"hyperparameters": {
"var_smoothing": [1e-9, 1e-10, 1e-11, 1e-12]
}
},
{
"name": "AdaBoost",
"estimator": AdaBoostClassifier(),
"hyperparameters": {
"n_estimators": [50, 100, 200],
"learning_rate": [0.01, 0.1, 1],
"algorithm": ["SAMME", "SAMME.R"]
}
},
best_models[model['name']] = best_model
Train models
In [38]: # Train Logistic Regression model
log_reg_model.fit(X_train, y_train)
Out[38]: ▾ AdaBoostClassifier
AdaBoostClassifier(learning_rate=0.1)
Features importance
In [39]: # fit the model
ab_model.fit(X_train, y_train)