demo python ml
| Дмитрий Личко
Скопировать в проект Демо проект python ноутбука с обучением XGBoost модели и выводом графиков
Пример Python ML ноутбука
1. Установка библиотек
[1] Python
await sq.install("matplotlib", "vega-datasets", "scikit-learn", "xgboost", quiet=True)
[2] Python
import pandas as pd
from vega_datasets import data
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import xgboost as xgb
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import numpy as np
2. Загрузка данных
[3] Python
10 строк × 9 колонок
cars = data.cars()
df = cars.dropna(subset=["Miles_per_Gallon", "Horsepower", "Weight_in_lbs"]).copy()
df["Year"] = pd.to_numeric(df["Year"], errors="coerce")
df = df.dropna(subset=["Year"])
df["Year"] = df["Year"].astype(int)
print(f"Строк: {len(df)}, колонок: {df.shape[1]}")
print(f"Годы: {df['Year'].min()}–{df['Year'].max()}")
print(f"Страны (Origin): {df['Origin'].unique().tolist()}")
df.head(10)
▸ Текст
Строк: 392, колонок: 9Годы: -1883897856–1971191808Страны (Origin): ['USA', 'Japan', 'Europe']▸ Таблица
| # | Name string | Year int | Origin string | Cylinders int | Horsepower float | Acceleration float | Displacement float | Weight_in_lbs int | Miles_per_Gallon float |
|---|---|---|---|---|---|---|---|---|---|
| 0 | chevrolet chevelle malibu | 0 | USA | 8 | 130 | 12 | 307 | 3504 | 18 |
| 1 | buick skylark 320 | 0 | USA | 8 | 165 | 11.5 | 350 | 3693 | 15 |
| 2 | plymouth satellite | 0 | USA | 8 | 150 | 11 | 318 | 3436 | 18 |
| 3 | amc rebel sst | 0 | USA | 8 | 150 | 12 | 304 | 3433 | 16 |
| 4 | ford torino | 0 | USA | 8 | 140 | 10.5 | 302 | 3449 | 17 |
| 5 | ford galaxie 500 | 0 | USA | 8 | 198 | 10 | 429 | 4341 | 15 |
| 6 | chevrolet impala | 0 | USA | 8 | 220 | 9 | 454 | 4354 | 14 |
| 7 | plymouth fury iii | 0 | USA | 8 | 215 | 8.5 | 440 | 4312 | 14 |
| 8 | pontiac catalina | 0 | USA | 8 | 225 | 10 | 455 | 4425 | 14 |
| 9 | amc ambassador dpl | 0 | USA | 8 | 190 | 8.5 | 390 | 3850 | 15 |
| 10 строк × 9 колонок | |||||||||
[4] Python
8 строк × 6 колонок
numeric = ["Miles_per_Gallon", "Horsepower", "Weight_in_lbs", "Acceleration", "Displacement", "Cylinders"]
df[numeric].describe()
▸ Таблица
| # | Cylinders float | Horsepower float | Acceleration float | Displacement float | Weight_in_lbs float | Miles_per_Gallon float |
|---|---|---|---|---|---|---|
| 0 | 392 | 392 | 392 | 392 | 392 | 392 |
| 1 | 5.4719387755 | 104.4693877551 | 15.5413265306 | 194.4119897959 | 2977.5841836735 | 23.4459183673 |
| 2 | 1.7057832475 | 38.4911599328 | 2.7588641192 | 104.6440039089 | 849.4025600429 | 7.8050074866 |
| 3 | 3 | 46 | 8 | 68 | 1613 | 9 |
| 4 | 4 | 75 | 13.775 | 105 | 2225.25 | 17 |
| 5 | 4 | 93.5 | 15.5 | 151 | 2803.5 | 22.75 |
| 6 | 8 | 126 | 17.025 | 275.75 | 3614.75 | 29 |
| 7 | 8 | 230 | 24.8 | 455 | 5140 | 46.6 |
| 8 строк × 6 колонок | ||||||
3. Генерация графиков
[5] Python
3 изображения
# 1) Распределение MPG
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.hist(df["Miles_per_Gallon"], bins=20, color="#4c78a8", edgecolor="white")
ax.set_title("Распределение расхода топлива (MPG)")
ax.set_xlabel("Miles per Gallon")
ax.set_ylabel("Количество авто")
plt.tight_layout()
plt.show()
# 2) Мощность vs расход, цвет по стране происхождения
fig, ax = plt.subplots(figsize=(7, 4))
for origin, part in df.groupby("Origin"):
ax.scatter(part["Horsepower"], part["Miles_per_Gallon"], label=origin, alpha=0.75, s=35)
ax.set_title("Мощность vs расход топлива")
ax.set_xlabel("Horsepower")
ax.set_ylabel("MPG")
ax.legend(title="Origin")
plt.tight_layout()
plt.show()
# 3) Средний MPG по годам выпуска
mpg_by_year = df.groupby("Year")["Miles_per_Gallon"].mean().sort_index()
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(mpg_by_year.index, mpg_by_year.values, marker="o", color="#f58518")
ax.set_title("Средний MPG по году выпуска")
ax.set_xlabel("Year")
ax.set_ylabel("MPG")
plt.tight_layout()
plt.show()
[6] Python
5 строк × 8 колонок
features = pd.get_dummies(
df[["Cylinders", "Displacement", "Horsepower", "Weight_in_lbs", "Acceleration", "Year", "Origin"]],
columns=["Origin"],
drop_first=True,
)
target = df["Miles_per_Gallon"]
X_train, X_test, y_train, y_test = train_test_split(
features, target, test_size=0.25, random_state=42
)
print(f"Train: {len(X_train)}, test: {len(X_test)}")
print(f"Признаков: {X_train.shape[1]}")
features.head()
▸ Текст
Train: 294, test: 98Признаков: 8▸ Таблица
| # | Year int | Cylinders int | Horsepower float | Origin_USA bool | Acceleration float | Displacement float | Origin_Japan bool | Weight_in_lbs int |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 8 | 130 | true | 12 | 307 | false | 3504 |
| 1 | 0 | 8 | 165 | true | 11.5 | 350 | false | 3693 |
| 2 | 0 | 8 | 150 | true | 11 | 318 | false | 3436 |
| 3 | 0 | 8 | 150 | true | 12 | 304 | false | 3433 |
| 4 | 0 | 8 | 140 | true | 10.5 | 302 | false | 3449 |
| 5 строк × 8 колонок | ||||||||
4. Обучение модели
[7] Python
3 строки вывода
model = xgb.XGBRegressor(
n_estimators=200,
max_depth=4,
learning_rate=0.08,
subsample=0.9,
colsample_bytree=0.9,
random_state=42,
)
model.fit(X_train, y_train)
pred = model.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = float(np.sqrt(mean_squared_error(y_test, pred)))
r2 = r2_score(y_test, pred)
print(f"MAE: {mae:.2f} mpg")
print(f"RMSE: {rmse:.2f} mpg")
print(f"R²: {r2:.3f}")
▸ Текст
MAE: 1.91 mpgRMSE: 2.82 mpgR²: 0.842[8] Python
2 изображения
# Факт vs прогноз
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(y_test, pred, alpha=0.7, color="#54a24b")
lo, hi = y_test.min(), y_test.max()
ax.plot([lo, hi], [lo, hi], "--", color="#888")
ax.set_title("Факт vs прогноз (test)")
ax.set_xlabel("Фактический MPG")
ax.set_ylabel("Прогноз MPG")
plt.tight_layout()
plt.show()
# Важность признаков
imp = pd.Series(model.feature_importances_, index=features.columns).sort_values(ascending=True)
fig, ax = plt.subplots(figsize=(7, 5))
imp.tail(12).plot(kind="barh", ax=ax, color="#4c78a8")
ax.set_title("Топ признаков (XGBoost)")
ax.set_xlabel("importance")
plt.tight_layout()
plt.show()