IIS_2023_1/verina_daria_lab_5/main.py
2023-11-23 02:33:04 +04:00

59 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# Загрузка данных
data = pd.read_csv('person_types.csv')
# Выбор переменных для модели
features = ['ACTIVITY_LEVEL', 'WEIGHT', 'HEIGHT']
# Отбор нужных столбцов
df = data[features + ['SEX']]
# Удаление строк с пропущенными значениями
df = df.dropna()
# Преобразование строковых значений в числа
le = LabelEncoder()
df['ACTIVITY_LEVEL'] = le.fit_transform(df['ACTIVITY_LEVEL'])
# Разделение на признаки и целевую переменную
X = df.drop('SEX', axis=1)
y = df['SEX']
# Разделение на тренировочный и тестовый наборы
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Стандартизация признаков
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Создание и обучение логистической регрессии
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
# Предсказание на тестовом наборе
y_pred = model.predict(X_test_scaled)
# Оценка качества модели
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print(f'Accuracy: {accuracy}')
print(f'Confusion Matrix:\n{conf_matrix}')
print(f'Classification Report:\n{class_report}')
# Визуализация результатов
plt.scatter(X_test['WEIGHT'], y_test, color='black', label='Actual')
plt.scatter(X_test['WEIGHT'], y_pred, color='blue', label='Predicted', marker='x')
plt.xlabel('Weight')
plt.ylabel('Sex')
plt.legend()
plt.show()