Added automizing for laptops
This commit is contained in:
parent
d5184e4419
commit
920c3d4831
@ -62,8 +62,8 @@ def get_unique_laptops():
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
@router.get('/get_unique_data_tv', summary="Get unique data for tvs species")
|
||||
def get_unique_laptops():
|
||||
def get_unique_tvs():
|
||||
try:
|
||||
return tv_service.get_unique_data()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
BIN
requirements.txt
BIN
requirements.txt
Binary file not shown.
@ -10,7 +10,7 @@ import json
|
||||
import os
|
||||
|
||||
# Шаг 1: Загрузка данных
|
||||
df = pd.read_csv('../../../../datasets/laptops.csv')
|
||||
df = pd.read_csv('datasets/laptops.csv')
|
||||
|
||||
# Шаг 2: Проверка и очистка имен столбцов
|
||||
df.columns = df.columns.str.strip().str.lower()
|
||||
@ -95,7 +95,7 @@ unique_values = {
|
||||
}
|
||||
|
||||
# Создание директории, если она не существует
|
||||
output_dir = 'columns'
|
||||
output_dir = 'services/ml/scripts/modelBuilders/columns'
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
with open(os.path.join(output_dir, 'unique_values_laptop.json'), 'w', encoding='utf-8') as f:
|
||||
@ -139,18 +139,13 @@ best_model = grid_search.best_estimator_
|
||||
|
||||
# Шаг 12: Предсказания и оценка
|
||||
y_pred = best_model.predict(X_test)
|
||||
mae = mean_absolute_error(y_test, y_pred)
|
||||
rmse = mean_squared_error(y_test, y_pred, squared=False)
|
||||
r2 = r2_score(y_test, y_pred)
|
||||
print(f"Лучшие параметры: {grid_search.best_params_}")
|
||||
print(f"Random Forest - MAE: {mae}, RMSE: {rmse}, R²: {r2}")
|
||||
|
||||
# Шаг 13: Сохранение модели
|
||||
feature_columns = X.columns.tolist()
|
||||
joblib.dump(feature_columns, '../../laptopML/feature_columns.pkl')
|
||||
joblib.dump(best_model, '../../laptopML/laptop_price_model.pkl')
|
||||
joblib.dump(poly, '../../laptopML/poly_transformer.pkl')
|
||||
joblib.dump(scaler, '../../laptopML/scaler.pkl')
|
||||
joblib.dump(feature_columns, 'services/ml/laptopML/feature_columns.pkl')
|
||||
joblib.dump(best_model, 'services/ml/laptopML/laptop_price_model.pkl')
|
||||
joblib.dump(poly, 'services/ml/laptopML/poly_transformer.pkl')
|
||||
joblib.dump(scaler, 'services/ml/laptopML/scaler.pkl')
|
||||
print("Модель, трансформер и скейлер сохранены.")
|
||||
|
||||
# Шаг 15: Важность признаков
|
||||
|
@ -1,11 +1,21 @@
|
||||
import subprocess
|
||||
import pandas as pd
|
||||
import joblib
|
||||
import json
|
||||
import os
|
||||
from typing import List, Dict
|
||||
from schemas.schemas import LaptopCreate, LaptopResponse, PredictPriceResponse
|
||||
|
||||
class LaptopService:
|
||||
def __init__(self, model_path: str, feature_columns_path: str, poly_path: str, scaler_path: str):
|
||||
self.script_path = "services/ml/scripts/modelBuilders/modelBuilderLaptop.py"
|
||||
|
||||
# Проверка наличия модели, если её нет — создание
|
||||
if not os.path.exists(model_path) or not os.path.exists(feature_columns_path) or not os.path.exists(poly_path) or not os.path.exists(scaler_path):
|
||||
print("Необходимые файлы модели отсутствуют. Запускаем построение модели...")
|
||||
self.run_model_builder()
|
||||
|
||||
# Загрузка модели и связанных файлов
|
||||
try:
|
||||
self.model = joblib.load(model_path)
|
||||
except FileNotFoundError:
|
||||
@ -28,6 +38,29 @@ class LaptopService:
|
||||
except Exception as e:
|
||||
raise Exception(f"Error loading polynomial transformer or scaler: {str(e)}")
|
||||
|
||||
def run_model_builder(self):
|
||||
# Убедитесь, что путь к скрипту корректен
|
||||
if not os.path.exists(self.script_path):
|
||||
raise FileNotFoundError(f"Скрипт {self.script_path} не найден.")
|
||||
|
||||
try:
|
||||
print(f"Запускаем скрипт {self.script_path} для создания модели...")
|
||||
result = subprocess.run(
|
||||
['python', self.script_path],
|
||||
stdout=subprocess.PIPE, # Перенаправляем stdout
|
||||
stderr=subprocess.PIPE, # Перенаправляем stderr
|
||||
text=True # Декодируем вывод в текст
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
raise Exception(f"Ошибка выполнения скрипта: {result.stderr}")
|
||||
else:
|
||||
print("Модель успешно создана.")
|
||||
print(result.stdout)
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Не удалось выполнить скрипт: {str(e)}")
|
||||
|
||||
def predict_price(self, data: Dict[str, any]) -> PredictPriceResponse:
|
||||
# Преобразование данных в DataFrame
|
||||
input_df = pd.DataFrame([data])
|
||||
|
Loading…
x
Reference in New Issue
Block a user