-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_ml_model.py
More file actions
76 lines (61 loc) · 2.59 KB
/
train_ml_model.py
File metadata and controls
76 lines (61 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import pickle
import os
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
np.random.seed(42)
# Нормальные транзакции
normal_amounts = np.random.uniform(100, 10000, 60)
normal_hours = np.random.randint(8, 22, 60) # Днем
normal_weekend = np.random.choice([0, 1], 60, p=[0.7, 0.3])
normal_age = np.random.uniform(180, 3650, 60) # 6 мес - 10 лет
# Мошеннические транзакции
fraud_amounts = np.random.uniform(50000, 500000, 40)
fraud_hours = np.random.choice([0, 1, 2, 3, 22, 23], 40) # Ночью
fraud_weekend = np.random.choice([0, 1], 40, p=[0.3, 0.7])
fraud_age = np.random.uniform(1, 30, 40) # Очень новые аккаунты
# Объединяем
X_normal = np.column_stack([normal_amounts, normal_hours, normal_weekend, normal_age])
X_fraud = np.column_stack([fraud_amounts, fraud_hours, fraud_weekend, fraud_age])
X = np.vstack([X_normal, X_fraud])
y = np.hstack([np.zeros(60), np.ones(40)])
# Разделяем на train/test
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Нормализуем
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Используем Random Forest
model = RandomForestClassifier(
n_estimators=50, max_depth=5, random_state=42 # 50 деревьев
)
model.fit(X_train_scaled, y_train)
# Оцениваем точность
train_acc = model.score(X_train_scaled, y_train)
test_acc = model.score(X_test_scaled, y_test)
# Сохраняем
model_data = {
"model": model,
"scaler": scaler,
"version": "1.0",
"train_accuracy": train_acc,
"test_accuracy": test_acc,
"features": ["amount", "hour_of_day", "is_weekend", "account_age_days"],
"trained_at": "2025-10-24",
}
os.makedirs("app/static", exist_ok=True)
with open("app/static/fraud_model_v1.pkl", "wb") as f:
pickle.dump(model_data, f)
print("✅ Model trained and saved to app/static/fraud_model_v1.pkl")
print(f"📊 Train accuracy: {train_acc:.2%}")
print(f"📊 Test accuracy: {test_acc:.2%}")
print(f"🌲 Model: RandomForest with {getattr(model, 'n_estimators', 'unknown')} trees")
print(f"📋 Features: {model_data['features']}")
test_example = scaler.transform([[150000, 3, 1, 2]])
fraud_prob = model.predict_proba(test_example)[0][1]
print("\n🔍 Test prediction:")
print(" Transaction: 150,000 руб at 3 AM, weekend, 2 days old account")
print(f" Fraud probability: {fraud_prob:.2%}")