Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- from sklearn.model_selection import train_test_split
- from sklearn.linear_model import LogisticRegression
- from sklearn.preprocessing import StandardScaler
- from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
- # прочитаем из csv-файла данные о параметрах сетей и их устойчивости
- electrical_grid = pd.read_csv('/datasets/Electrical_Grid_Stability.csv', sep = ';')
- print('Размер датасета:', electrical_grid.shape)
- electrical_grid.head()
- # посмотрим, как соотносятся классы набора данных
- print('Соотношение классов:\n', electrical_grid['stability'].value_counts())
- # разделим наши данные на признаки (матрица X) и целевую переменную (y)
- X = electrical_grid.drop('stability', axis = 1)
- y = electrical_grid['stability']
- # разделяем модель на обучающую и валидационную выборку
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
- # зададим алгоритм для нашей модели
- model = LogisticRegression()
- # обучим модель
- model.fit(X_train, y_train)
- # воспользуемся уже обученной моделью, чтобы сделать прогнозы
- probabilities = model.predict_proba(X_test)[:,1]
- # бинарный прогноз
- predictions = model.predict(X_test)
- # выведите все изученные метрики для полученного прогноза
- print('Метрики при автоматическом прогнозе с помощью predict')
- print('Accuracy: {:.2f}'.format(accuracy_score(y_test, predictions)))
- print('Precision: {:.2f}'.format(precision_score(y_test, predictions)))
- print('Recall: {:.2f}'.format(recall_score(y_test, predictions)))
- print('F1: {:.2f}\n'.format(f1_score(y_test, predictions)))
- # задайте порог
- threshold = 0.4
- # на основании вероятностей и соотношения классов рассчитайте predict
- custom_predictions = [0 if i<threshold else 1 for i in probabilities]
- # выведите все изученные метрики для прогноза по новому порогу
- print('Метрики для прогноза с кастомным порогом')
- print('Accuracy for custom: {:.2f}'.format(accuracy_score(y_test, custom_predictions)))
- print('Precision for custom: {:.2f}'.format(precision_score(y_test, custom_predictions)))
- print('Recall for custom: {:.2f}'.format(recall_score(y_test, custom_predictions)))
- print('F1 for custom: {:.2f}'.format(f1_score(y_test, custom_predictions)))
Advertisement
Add Comment
Please, Sign In to add comment