Compare commits
6 Commits
kutygin_an
...
tepechin_k
| Author | SHA1 | Date | |
|---|---|---|---|
| c47e1e3012 | |||
| 5729ed64a9 | |||
| 49d703350e | |||
| d29da45383 | |||
| 90954dfa89 | |||
| a8c58683dd |
118
kutygin_andre_lab_3/README.md
Normal file
118
kutygin_andre_lab_3/README.md
Normal file
@@ -0,0 +1,118 @@
|
||||
**Задание**
|
||||
***
|
||||
Решите с помощью библиотечной реализации дерева решений задачу из лабораторной работы «Веб-сервис «Дерево решений» по предмету «Методы искусственного интеллекта»на 99% ваших данных. Проверьте работу модели на оставшемся проценте, сделайте вывод
|
||||
|
||||
**Как запустить лабораторную**
|
||||
***
|
||||
Запустить файл main.py
|
||||
|
||||
**Используемые технологии**
|
||||
***
|
||||
Библиотеки pandas, scikit-learn, matplotlib, их компоненты
|
||||
|
||||
**Описание лабораторной (программы)**
|
||||
***
|
||||
В данном коде мы создаем и обучаем модель дерева решений для прогнозирования инцидентов с НЛО на основе набора данных.
|
||||
|
||||
1. В первой строке кода мы загружаем данные из CSV-файла 'ufo_data_nuforc.csv' с помощью функции pd.read_csv(). Эти данные содержат информацию о различных инцидентах с НЛО.
|
||||
2. Далее мы выбираем набор признаков, в данном случае, эти признаки - населенность и время, которые будут использоваться для обучения модели, и сохраняем их в переменную features.
|
||||
3. Затем преобразуем категориальные признаки в числовой вид при помощи функции pd.get_dummies(). Это необходимо, так как модель дерева решений работает только с числовыми данными.
|
||||
4. После этого мы разделяем данные на обучающую и тестовую выборки с помощью функции train_test_split(). Обучающая выборка будет использоваться для обучения модели, а тестовая - для проверки ее точности.
|
||||
5. Создаем модель дерева решений с помощью класса DecisionTreeClassifier() из библиотеки sklearn.tree.
|
||||
6. Обучаем модель на обучающей выборке с помощью метода fit(). В процессе обучения модель настраивает параметры дерева решений, чтобы лучше предсказывать целевой признак.
|
||||
7. После обучения модели, мы производим прогнозы на тестовых данных с помощью метода predict().
|
||||
8. Оцениваем точность модели на тестовой выборке с помощью метода accuracy_score() из библиотеки sklearn.metrics. Этот метод сравнивает фактические значения целевого признака с предсказанными и возвращает точность модели.
|
||||
9. Наконец, выводим точность модели на тестовой выборке, чтобы оценить, насколько хорошо модель предсказывает инциденты с НЛО.
|
||||
10. Также, код визуализирует данные в виде графика с помощью библиотеки matplotlib.pyplot, отображая фактические значения целевого признака и предсказания модели. Это помогает наглядно оценить, насколько близки предсказания модели к реальным значениям.
|
||||
**Результат**
|
||||
***
|
||||
Точность модели на тестовой выборке: 0.1377245508982036
|
||||
Прогнозы по оставшемуся проценту данных: 'cylinder' 'circle' 'sphere' 'disk' 'disk' 'fireball' 'disk' 'oval'
|
||||
'circle' 'disk' 'disk' 'other' 'light' 'light' 'oval' 'fireball' 'light'
|
||||
'rectangle' 'chevron' 'unknown' 'sphere' 'oval' 'light' 'circle'
|
||||
'unknown' 'unknown' 'disk' 'triangle' 'triangle' 'unknown' 'formation'
|
||||
'unknown' 'cigar' 'unknown' 'light' 'other' 'rectangle' 'light' 'other'
|
||||
'light' 'cylinder' 'delta' 'sphere' 'other' 'changing' 'fireball'
|
||||
'cylinder' 'cigar' 'circle' 'triangle' 'light' 'fireball' 'fireball'
|
||||
'sphere' 'circle' 'light' 'chevron' 'oval' 'oval' 'light' 'unknown'
|
||||
'triangle' 'other' 'rectangle' 'triangle' 'triangle' 'flash' 'unknown'
|
||||
'sphere' 'unknown' 'other' 'circle' 'oval' 'light' 'oval' 'formation'
|
||||
'sphere' 'triangle' 'changing' 'sphere' 'oval' 'unknown' 'circle'
|
||||
'circle' 'flash' 'light' 'light' 'sphere' 'other' 'other' 'egg' 'unknown'
|
||||
'other' 'light' 'light' 'disk' 'diamond' 'oval' 'unknown' 'light'
|
||||
'triangle' 'other' 'light' 'disk' 'unknown' 'light' 'changing' 'sphere'
|
||||
'triangle' 'circle' 'flash' 'sphere' 'light' 'unknown' 'oval' 'formation'
|
||||
'light' 'circle' 'unknown' 'other' 'triangle' 'other' 'light' 'disk'
|
||||
'formation' 'oval' 'triangle' 'triangle' 'light' 'formation' 'oval'
|
||||
'light' 'light' 'oval' 'disk' 'sphere' 'egg' 'unknown' 'unknown'
|
||||
'unknown' 'light' 'disk' 'changing' 'light' 'light' 'circle' 'circle'
|
||||
'formation' 'light' 'light' 'cigar' 'light' 'triangle' 'oval' 'fireball'
|
||||
'cylinder' 'other' 'circle' 'egg' 'changing' 'triangle' 'circle' 'other'
|
||||
'oval' 'disk' 'light' 'flash' 'fireball' 'circle' 'circle' 'circle'
|
||||
'circle' 'light' 'disk' 'fireball' 'other' 'sphere' 'light' 'changing'
|
||||
'cigar' 'light' 'cylinder' 'rectangle' 'chevron' 'light' 'light' 'light'
|
||||
'light' 'circle' 'circle' 'light' 'light' 'circle' 'sphere' 'triangle'
|
||||
'light' 'egg' 'circle' 'fireball' 'sphere' 'sphere' 'triangle' 'light'
|
||||
'other' 'cigar' 'sphere' 'sphere' 'fireball' 'light' 'light' 'disk'
|
||||
'oval' 'oval' 'other' 'cigar' 'triangle' 'light' 'light' 'light' 'disk'
|
||||
'light' 'light' 'light' 'light' 'other' 'light' 'teardrop' 'triangle'
|
||||
'teardrop' 'fireball' 'sphere' 'cylinder' 'fireball' 'circle' 'egg'
|
||||
'sphere' 'disk' 'chevron' 'triangle' 'light' 'other' 'light' 'circle'
|
||||
'rectangle' 'fireball' 'formation' 'light' 'light' 'circle' 'light'
|
||||
'light' 'formation' 'light' 'triangle' 'light' 'oval' 'light' 'unknown'
|
||||
'fireball' 'diamond' 'light' 'circle' 'light' 'triangle' 'oval' 'oval'
|
||||
'cylinder' 'circle' 'light' 'disk' 'light' 'sphere' 'circle' 'light'
|
||||
'triangle' 'light' 'fireball' 'triangle' 'light' 'flash' 'triangle' 'egg'
|
||||
'disk' 'oval' 'circle' 'flash' 'light' 'oval' 'sphere' 'light' 'triangle'
|
||||
'other' 'chevron' 'other' 'circle' 'unknown' 'unknown' 'sphere' 'light'
|
||||
'cigar' 'light' 'fireball' 'circle' 'diamond' 'fireball' 'triangle'
|
||||
'diamond' 'sphere' 'circle' 'chevron' 'cylinder' 'light' 'circle'
|
||||
'fireball' 'unknown' 'light' 'circle' 'fireball' 'light' 'fireball'
|
||||
'fireball' 'fireball' 'light' 'sphere' 'light' 'sphere' 'sphere'
|
||||
'formation' 'light' 'fireball' 'fireball' 'disk' 'disk' 'circle'
|
||||
'rectangle' 'unknown' 'disk' 'unknown' 'disk' 'triangle' 'other' 'sphere'
|
||||
'diamond' 'light' 'light' 'unknown' 'sphere' 'circle' 'disk' 'circle'
|
||||
'oval' 'changing' 'other' 'other' 'disk' 'unknown' 'unknown' 'disk'
|
||||
'rectangle' 'disk' 'light' 'oval' 'unknown' 'sphere' 'light' 'changing'
|
||||
'disk' 'disk' 'other' 'other' 'disk' 'cylinder' 'disk' 'rectangle'
|
||||
'light' 'disk' 'disk' 'light' 'fireball' 'formation' 'cigar' 'oval'
|
||||
'fireball' 'unknown' 'disk' 'light' 'light' 'triangle' 'triangle' 'light'
|
||||
'sphere' 'triangle' 'sphere' 'circle' 'light' 'oval' 'oval' 'circle'
|
||||
'oval' 'rectangle' 'disk' 'oval' 'light' 'light' 'other' 'cigar'
|
||||
'triangle' 'disk' 'cigar' 'other' 'triangle' 'egg' 'unknown' 'triangle'
|
||||
'light' 'triangle' 'disk' 'changing' 'triangle' 'disk' 'disk' 'rectangle'
|
||||
'other' 'triangle' 'triangle' 'formation' 'triangle' 'egg' 'sphere'
|
||||
'fireball' 'triangle' 'rectangle' 'light' 'triangle' 'triangle' 'other'
|
||||
'light' 'light' 'disk' 'fireball' 'light' 'disk' 'oval' 'triangle'
|
||||
'other' 'fireball' 'light' 'light' 'triangle' 'unknown' 'cigar' 'light'
|
||||
'unknown' 'chevron' 'formation' 'disk' 'cigar' 'light' 'sphere' 'cigar'
|
||||
'unknown' 'triangle' 'other' 'light' 'light' 'triangle' 'diamond' 'light'
|
||||
'triangle' 'oval' 'changing' 'light' 'flash' 'circle' 'oval' 'other'
|
||||
'sphere' 'circle' 'triangle' 'unknown' 'teardrop' 'unknown' 'fireball'
|
||||
'light' 'light' 'cigar' 'cigar' 'light' 'fireball' 'other' 'egg' 'light'
|
||||
'other' 'unknown' 'unknown' 'changing' 'circle' 'light' 'other' 'unknown'
|
||||
'unknown' 'light' 'other' 'light' 'unknown' 'cylinder' 'triangle'
|
||||
'circle' 'light' 'circle' 'circle' 'circle' 'light' 'light' 'changing'
|
||||
'changing' 'circle' 'circle' 'triangle' 'triangle' 'light' 'light'
|
||||
'light' 'light' 'other' 'changing' 'triangle' 'cylinder' 'light'
|
||||
'unknown' 'circle' 'disk' 'sphere' 'oval' 'formation' 'teardrop'
|
||||
'triangle' 'chevron' 'light' 'unknown' 'unknown' 'other' 'egg' 'circle'
|
||||
'oval' 'cigar' 'unknown' 'chevron' 'oval' 'cigar' 'fireball' 'circle'
|
||||
'unknown' 'light' 'sphere' 'fireball' 'changing' 'light' 'circle'
|
||||
'unknown' 'fireball' 'light' 'sphere' 'light' 'formation' 'circle'
|
||||
'fireball' 'formation' 'formation' 'formation' 'light' 'other' 'light'
|
||||
'light' 'circle' 'diamond' 'oval' 'circle' 'oval' 'triangle' 'light'
|
||||
'disk' 'light' 'other' 'triangle' 'triangle' 'cylinder' 'disk' 'cylinder'
|
||||
'light' 'oval' 'cigar' 'circle' 'disk' 'light' 'unknown' 'circle' 'other'
|
||||
'light' 'light' 'light' 'unknown' 'triangle' 'other' 'disk' 'cylinder'
|
||||
'triangle' 'oval' 'disk' 'light' 'triangle' 'circle' 'light' 'other'
|
||||
'light' 'other' 'circle' 'disk' 'other' 'triangle' 'oval' 'unknown'
|
||||
'light' 'triangle' 'unknown' 'circle' 'unknown' 'light' 'fireball'
|
||||
'fireball' 'rectangle' 'light' 'formation' 'unknown' 'light' 'light'
|
||||
'formation' 'fireball' 'light' 'light' 'other' 'unknown' 'light'
|
||||
'triangle' 'fireball' 'triangle' 'triangle' 'flash' 'circle' 'triangle'
|
||||
'disk' 'light' 'unknown' 'light' 'light' 'fireball' 'circle' 'unknown'
|
||||
'unknown' 'circle' 'disk' 'chevron' 'disk' 'disk' 'triangle' 'light'
|
||||
'light' 'disk'
|
||||
|
||||
***Вывод:*** Наша модель дерева решений показала низкую точность предсказаний (Точность модели на тестовой выборке: 0.1377245508982036), что означает, что она не очень хорошо предсказывает форму НЛО на основе выбранных признаков (население и время). Из-за чего можно сделать вывод, что возможно, эти признаки недостаточно информативны или недостаточно связаны с формой НЛО.
|
||||
39
kutygin_andre_lab_3/main.py
Normal file
39
kutygin_andre_lab_3/main.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import pandas as pd
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
from sklearn.metrics import accuracy_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
# Загрузка данных
|
||||
data = pd.read_csv('ufo_sighting_data.csv')
|
||||
|
||||
# Выбор признаков
|
||||
features = [ 'length_of_encounter_seconds', 'latitude', 'longitude']
|
||||
target = 'UFO_shape'
|
||||
# Удаление строк содержащих NaN
|
||||
data.dropna(inplace=True)
|
||||
|
||||
# Удаление столбцов содержащих NaN
|
||||
data.dropna(axis='columns', inplace=True)
|
||||
|
||||
# Разделение данных на обучающую и тестовую выборки
|
||||
train_data, test_data, train_labels, test_labels = train_test_split(data[features], data[target], test_size=0.2, random_state=42)
|
||||
|
||||
# Создание и обучение модели дерева решений
|
||||
model = DecisionTreeClassifier()
|
||||
model.fit(train_data, train_labels)
|
||||
|
||||
# Прогнозирование на тестовой выборке
|
||||
predictions = model.predict(test_data)
|
||||
|
||||
# Оценка точности модели
|
||||
accuracy = accuracy_score(test_labels, predictions)
|
||||
print('Точность модели на тестовой выборке:', accuracy)
|
||||
|
||||
# Прогнозирование на оставшемся проценте данных
|
||||
remaining_data = data.drop(test_data.index)
|
||||
remaining_predictions = model.predict(remaining_data[features])
|
||||
|
||||
# Вывод результатов
|
||||
print('Прогнозы по оставшемуся проценту данных:', remaining_predictions)
|
||||
|
||||
# Сделайте необходимые выводы
|
||||
1
kutygin_andre_lab_3/ufo_sighting_data.csv
Normal file
1
kutygin_andre_lab_3/ufo_sighting_data.csv
Normal file
File diff suppressed because one or more lines are too long
35
tepechin_kirill_lab_1/README.md
Normal file
35
tepechin_kirill_lab_1/README.md
Normal file
@@ -0,0 +1,35 @@
|
||||
## Лабораторная работа №1, ПИбд-42 Тепечин Кирилл, Вариант 26(5)
|
||||
|
||||
### Задание
|
||||
#### Данные:
|
||||
make_circles (noise=0.2, factor=0.5, random_state=rs)
|
||||
#### Модели:
|
||||
* Линейная регрессия
|
||||
* Полиномиальная регрессия (со степенью 4)
|
||||
* Гребневая полиномиальная регрессия (со степенью 4, alpha = 1.0)
|
||||
### Как запустить лабораторную работу:
|
||||
|
||||
Для запуска лабораторной работы необходимо запустить файл lab1.py
|
||||
|
||||
### Используемые технологии:
|
||||
|
||||
* Python 3.12
|
||||
* numpy
|
||||
* matplotlib
|
||||
* scikit-learn
|
||||
|
||||
### Что делает лабораторная работа:
|
||||
|
||||
Эта лабораторная работа создает и сравнивает различные модели регрессии для сгенерированного набора данных, оценивая их производительность на основе среднеквадратичной ошибки и визуализируя их предсказания на графиках.
|
||||
|
||||
### Результат:
|
||||
* *Линейная регрессия*, среднеквадратичная ошибка: 0.29507570583195913
|
||||
* *Полиноминальная регрессия*, среднеквадратичная ошибка: 0.1803255642844966
|
||||
* *Гребневая полиномиальная регрессия*, среднеквадратичная ошибка: 0.17274375314846807
|
||||
|
||||
### Вывод
|
||||
Самое маленькое значение mse у *Гребневая полиномиальная регрессия*
|
||||
|
||||
### График
|
||||
|
||||

|
||||
74
tepechin_kirill_lab_1/lab1.py
Normal file
74
tepechin_kirill_lab_1/lab1.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from matplotlib.colors import ListedColormap
|
||||
from sklearn.datasets import make_circles
|
||||
from sklearn.linear_model import LinearRegression
|
||||
from sklearn.linear_model import Ridge
|
||||
from sklearn.metrics import mean_squared_error
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.pipeline import make_pipeline
|
||||
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
|
||||
|
||||
rs = 42
|
||||
|
||||
X, y = make_circles(noise=0.2, factor=0.5, random_state=rs)
|
||||
X = StandardScaler().fit_transform(X)
|
||||
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4, random_state=rs)
|
||||
|
||||
# Инициализируем модели
|
||||
linear_model = LinearRegression()
|
||||
poly_model = make_pipeline(PolynomialFeatures(4), LinearRegression())
|
||||
ridge_model = make_pipeline(PolynomialFeatures(4), Ridge(alpha=1.0))
|
||||
|
||||
# Обучаем модели
|
||||
linear_model.fit(X_train, y_train)
|
||||
poly_model.fit(X_train, y_train)
|
||||
ridge_model.fit(X_train, y_train)
|
||||
|
||||
# Предсказываем значения для тестового набора
|
||||
y_pred_linear = linear_model.predict(X_test)
|
||||
y_pred_poly = poly_model.predict(X_test)
|
||||
y_pred_ridge = ridge_model.predict(X_test)
|
||||
|
||||
# Качество моделей
|
||||
mse_linear = mean_squared_error(y_test, y_pred_linear)
|
||||
mse_poly = mean_squared_error(y_test, y_pred_poly)
|
||||
mse_ridge = mean_squared_error(y_test, y_pred_ridge)
|
||||
models_data = [(linear_model, "Линейная", mse_linear), (poly_model, "Полиномиальная", mse_poly),
|
||||
(ridge_model, "Греб. полиномиальная", mse_ridge)]
|
||||
# Печатаем MSE
|
||||
print(f"mse линейная: {mse_linear}")
|
||||
print(f"mse полиномиальная: {mse_poly}")
|
||||
print(f"mse гребневая полиномиальная: {mse_ridge}")
|
||||
|
||||
cm = plt.cm.RdBu
|
||||
cm_bright = ListedColormap(['#FF0000', '#0000FF'])
|
||||
|
||||
fig, axs = plt.subplots(1, 3, figsize=(15, 7))
|
||||
fig.suptitle('Сравнение регрессионных моделей')
|
||||
|
||||
|
||||
# Функция отрисовки моделей
|
||||
def draw_plot(model_data, i):
|
||||
h = .02 # шаг регулярной сетки
|
||||
x0_min, x0_max = X[:, 0].min() - .5, X[:, 0].max() + .5
|
||||
x1_min, x1_max = X[:, 1].min() - .5, X[:, 1].max() + .5
|
||||
xx0, xx1 = np.meshgrid(np.arange(x0_min, x0_max, h), np.arange(x1_min, x1_max, h))
|
||||
Z = model_data[0].predict(np.c_[xx0.ravel(), xx1.ravel()]) # 3
|
||||
|
||||
Z = Z.reshape(xx0.shape)
|
||||
axs[i].contourf(xx0, xx1, Z, cmap=cm, alpha=.8)
|
||||
axs[i].set_xlim(xx0.min(), xx0.max())
|
||||
axs[i].set_ylim(xx0.min(), xx1.max())
|
||||
axs[i].set_xticks(())
|
||||
axs[i].set_yticks(())
|
||||
axs[i].set_title(model_data[1])
|
||||
axs[i].text(xx0.max() - .3, xx1.min() + .3, ('%.2f' % model_data[2]).lstrip('0'),
|
||||
size=15, horizontalalignment='right')
|
||||
axs[i].scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
|
||||
|
||||
|
||||
for i, model_data in enumerate(models_data):
|
||||
draw_plot(model_data, i)
|
||||
plt.savefig("plots.png")
|
||||
plt.show()
|
||||
BIN
tepechin_kirill_lab_1/plots.png
Normal file
BIN
tepechin_kirill_lab_1/plots.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
Reference in New Issue
Block a user