IIS_2023_1/arzamaskina_milana_lab_5/main.py

70 lines
2.8 KiB
Python
Raw Permalink Normal View History

2023-12-02 20:24:38 +04:00
import math
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.metrics import mean_squared_error
# По варианту 2:
# предсказание доли выбросов CO2 промышленной деятельностью
# от общего объёма выбросов CO2 страной в определённый год
# с помощью логистической регрессии
# Дополнительно: с помощью полиномиальной регрессии 3 степени
# Загружаем данные из файла
data = pd.read_csv('CO2.csv')
data = data.dropna()
data = data[data.Country != 'Global']
# Хеширование наименований стран
countries = {}
for country in data['Country']:
countries[country] = hash(country)
hash_column = []
for country in data['Country']:
hash_column.append(countries[country])
data.insert(loc=0, column='hashcode', value=hash_column)
# Добавление колонки "доля выбросов промышленным производством в стране за год"
procent_other = []
others = []
totals = []
for other in data['Other']:
others.append(other)
for total in data['Total']:
totals.append(total)
for i in range(len(others)):
procent_other.append(math.ceil(others[i]/totals[i]*100))
data.insert(loc=0, column='procent other', value=procent_other)
# Необходимые признаки
features = data[['Total', 'hashcode', 'Year']]
# Задача логистической регрессии
task = data['procent other']
# Разделение данных на обучающую и тестовую выборки
X_train, X_test, y_train, y_test = train_test_split(features, task, test_size=0.01, random_state=5)
# Применение логистической регрессии
model_logic = LogisticRegression(max_iter=1000)
model_logic.fit(X_train, y_train)
# Предсказание на тестовых данных
y_pred_logic = model_logic.predict(X_test)
# Полиномиальная регрессия (degree=3)
model_poly = make_pipeline(PolynomialFeatures(degree=3), LinearRegression())
model_poly.fit(X_train, y_train)
# Предсказание на тестовых данных
y_pred_poly = model_poly.predict(X_test)
# Оценка регрессионных моделей
poly_mse = mean_squared_error(y_test, y_pred_poly)
logic_mse = mean_squared_error(y_test, y_pred_logic)
print('Среднеквадратичная ошибка полиномиальной регрессии:', poly_mse)
print('Среднеквадратичная ошибка логистической регрессии:', logic_mse)