IIS_2023_1/verina_daria_lab_6/main.py
2023-11-23 02:58:17 +04:00

61 lines
1.8 KiB
Python

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# Load data
data = pd.read_csv('person_types.csv')
# Select variables for the model
features = ['HEIGHT', 'WEIGHT', 'ACTIVITY_LEVEL']
# Select relevant columns
df = data[features + ['SEX']]
# Drop rows with missing values
df = df.dropna()
# Convert string values to numerical for 'ACTIVITY_LEVEL'
le_activity = LabelEncoder()
df['ACTIVITY_LEVEL'] = le_activity.fit_transform(df['ACTIVITY_LEVEL'])
# Split into features and target variable
X = df.drop('SEX', axis=1)
y = df['SEX']
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Standardize features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Create and train MLPClassifier
model = MLPClassifier(random_state=42)
model.fit(X_train_scaled, y_train)
# Predict on the test set
y_pred = model.predict(X_test_scaled)
# Evaluate the model
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}')
# Visualize the results (e.g., a histogram)
plt.hist(y_pred, bins=np.arange(3)-0.5, alpha=0.75, color='blue', label='Predicted')
plt.hist(y_test, bins=np.arange(3)-0.5, alpha=0.5, color='green', label='Actual')
plt.xlabel('Sex')
plt.ylabel('Count')
plt.xticks([0, 1], ['Female', 'Male'])
plt.legend()
plt.show()