IIS_2023_1/tepechin_kirill_lab_6/lab6.py

47 lines
1.8 KiB
Python
Raw Normal View History

2023-12-01 17:03:52 +04:00
import pandas as pd
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.neural_network import MLPRegressor
# Загрузка данных
data = pd.read_csv("smoking_drinking_dataset.csv")
data = data.sample(frac=0.3, random_state=42)
# # Подготовка данных
data = pd.get_dummies(data, columns=['sex', 'DRK_YN'], drop_first=True)
# Разделение данных на признаки (X) и целевую переменную (y)
X = data.drop(columns=['SMK_stat_type_cd'])
y = data['SMK_stat_type_cd']
# Разделение данных
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Создание и обучение модели
model = MLPRegressor(hidden_layer_sizes=(100,1), max_iter=500, learning_rate_init=0.001, random_state=42, alpha=0.0001, activation='tanh', solver='adam')
#model = MLPRegressor(random_state=42)
model.fit(X_train, y_train)
# Предсказание на тестовом наборе
predictions = model.predict(X_test)
# Оценка модели
mse = mean_squared_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
print(f'Mean Squared Error: {mse}')
print(f'R-squared: {r2}')
# Выбор оптимальных параметров c помощью GridSearchCV
# param_grid = {'hidden_layer_sizes': [(50,50,50), (50,100,50), (100,1), (200,100)],
# 'activation': ['relu','tanh','logistic'],
# 'alpha': [0.0001, 0.05],
# 'max_iter': [50, 100, 500, 1000],
# 'learning_rate': ['constant','adaptive'],
# 'solver': ['adam', 'sgd']}
# estimator=MLPRegressor(max_iter=10000, random_state=42)
# grid = GridSearchCV(estimator, param_grid, n_jobs= -1, cv=5)
# grid.fit(X_train, y_train)
#
# print(grid.best_params_)