Spaces:
Sleeping
Sleeping
RafaelFonseca commited on
Commit ·
e50f22e
1
Parent(s): e0681c0
Add Django Django_webapp project to HF space
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Dockerfile +36 -0
- manage.py +22 -0
- myproject/__init__.py +0 -0
- myproject/__pycache__/__init__.cpython-312.pyc +0 -0
- myproject/__pycache__/settings.cpython-312.pyc +0 -0
- myproject/__pycache__/urls.cpython-312.pyc +0 -0
- myproject/__pycache__/wsgi.cpython-312.pyc +0 -0
- myproject/asgi.py +16 -0
- myproject/settings.py +105 -0
- myproject/urls.py +16 -0
- myproject/wsgi.py +16 -0
- requirements.txt +24 -0
- staticfiles/.gitkeep +0 -0
- webapp/__init__.py +0 -0
- webapp/__pycache__/__init__.cpython-312.pyc +0 -0
- webapp/__pycache__/admin.cpython-312.pyc +0 -0
- webapp/__pycache__/apps.cpython-312.pyc +0 -0
- webapp/__pycache__/forms.cpython-312.pyc +0 -0
- webapp/__pycache__/models.cpython-312.pyc +0 -0
- webapp/__pycache__/urls.cpython-312.pyc +0 -0
- webapp/__pycache__/views.cpython-312.pyc +0 -0
- webapp/admin.py +6 -0
- webapp/apps.py +6 -0
- webapp/forms.py +159 -0
- webapp/migrations/0001_initial.py +44 -0
- webapp/migrations/0002_userprofile.py +25 -0
- webapp/migrations/0003_savedmodel_description.py +18 -0
- webapp/migrations/0004_savedmodel_trained_on.py +18 -0
- webapp/migrations/0005_add_trained_on_field.py +13 -0
- webapp/migrations/__init__.py +0 -0
- webapp/migrations/__pycache__/0001_initial.cpython-312.pyc +0 -0
- webapp/migrations/__pycache__/0002_userprofile.cpython-312.pyc +0 -0
- webapp/migrations/__pycache__/0003_savedmodel_description.cpython-312.pyc +0 -0
- webapp/migrations/__pycache__/0004_savedmodel_trained_on.cpython-312.pyc +0 -0
- webapp/migrations/__pycache__/0005_add_trained_on_field.cpython-312.pyc +0 -0
- webapp/migrations/__pycache__/__init__.cpython-312.pyc +0 -0
- webapp/models.py +46 -0
- webapp/services/__init__.py +0 -0
- webapp/services/__pycache__/__init__.cpython-312.pyc +0 -0
- webapp/services/__pycache__/charts.cpython-312.pyc +0 -0
- webapp/services/__pycache__/inference.cpython-312.pyc +0 -0
- webapp/services/__pycache__/io_utils.cpython-312.pyc +0 -0
- webapp/services/__pycache__/ml_utils.cpython-312.pyc +0 -0
- webapp/services/__pycache__/training.cpython-312.pyc +0 -0
- webapp/services/charts.py +22 -0
- webapp/services/inference.py +326 -0
- webapp/services/io_utils.py +18 -0
- webapp/services/ml_utils.py +108 -0
- webapp/services/testing.py +132 -0
- webapp/services/training.py +940 -0
Dockerfile
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use Python 3.11 like your local/Render setup
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# System dependencies for numpy / pandas / sklearn / xgboost / shap, etc.
|
| 5 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 6 |
+
build-essential \
|
| 7 |
+
gcc \
|
| 8 |
+
g++ \
|
| 9 |
+
git \
|
| 10 |
+
libblas-dev \
|
| 11 |
+
liblapack-dev \
|
| 12 |
+
gfortran \
|
| 13 |
+
libgomp1 \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
+
|
| 16 |
+
# Workdir inside the container
|
| 17 |
+
WORKDIR /app
|
| 18 |
+
|
| 19 |
+
# Install Python packages
|
| 20 |
+
COPY requirements.txt .
|
| 21 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 22 |
+
|
| 23 |
+
# Copy the whole project
|
| 24 |
+
COPY . .
|
| 25 |
+
|
| 26 |
+
# HuggingFace exposes this port
|
| 27 |
+
ENV PORT=7860
|
| 28 |
+
ENV PYTHONUNBUFFERED=1
|
| 29 |
+
ENV DJANGO_SETTINGS_MODULE=myproject.settings
|
| 30 |
+
|
| 31 |
+
# Collect static files & run migrations
|
| 32 |
+
RUN python manage.py collectstatic --noinput || true
|
| 33 |
+
RUN python manage.py migrate --noinput || true
|
| 34 |
+
|
| 35 |
+
# Start Django via Gunicorn, listening on $PORT
|
| 36 |
+
CMD gunicorn myproject.wsgi:application --bind 0.0.0.0:${PORT} --workers 2
|
manage.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Django's command-line utility for administrative tasks."""
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
"""Run administrative tasks."""
|
| 9 |
+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
| 10 |
+
try:
|
| 11 |
+
from django.core.management import execute_from_command_line
|
| 12 |
+
except ImportError as exc:
|
| 13 |
+
raise ImportError(
|
| 14 |
+
"Couldn't import Django. Are you sure it's installed and "
|
| 15 |
+
"available on your PYTHONPATH environment variable? Did you "
|
| 16 |
+
"forget to activate a virtual environment?"
|
| 17 |
+
) from exc
|
| 18 |
+
execute_from_command_line(sys.argv)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == '__main__':
|
| 22 |
+
main()
|
myproject/__init__.py
ADDED
|
File without changes
|
myproject/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (194 Bytes). View file
|
|
|
myproject/__pycache__/settings.cpython-312.pyc
ADDED
|
Binary file (2.99 kB). View file
|
|
|
myproject/__pycache__/urls.cpython-312.pyc
ADDED
|
Binary file (841 Bytes). View file
|
|
|
myproject/__pycache__/wsgi.cpython-312.pyc
ADDED
|
Binary file (686 Bytes). View file
|
|
|
myproject/asgi.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ASGI config for myproject project.
|
| 3 |
+
|
| 4 |
+
It exposes the ASGI callable as a module-level variable named ``application``.
|
| 5 |
+
|
| 6 |
+
For more information on this file, see
|
| 7 |
+
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
from django.core.asgi import get_asgi_application
|
| 13 |
+
|
| 14 |
+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
| 15 |
+
|
| 16 |
+
application = get_asgi_application()
|
myproject/settings.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Django settings for myproject project.
|
| 3 |
+
|
| 4 |
+
Generated by 'django-admin startproject' using Django 5.2.3.
|
| 5 |
+
|
| 6 |
+
For more information on this file, see
|
| 7 |
+
https://docs.djangoproject.com/en/5.2/topics/settings/
|
| 8 |
+
|
| 9 |
+
For the full list of settings and their values, see
|
| 10 |
+
https://docs.djangoproject.com/en/5.2/ref/settings/
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
| 20 |
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
| 21 |
+
LOGIN_URL = '/login/'
|
| 22 |
+
LOGIN_REDIRECT_URL = '/landing/'
|
| 23 |
+
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
|
| 24 |
+
|
| 25 |
+
SECRET_KEY = 'django-insecure-&ew@l$*1zi4$0s^)nrrx#s$j09au5dmty@blo-j1ou+=v(v!(r'
|
| 26 |
+
DEBUG = True
|
| 27 |
+
|
| 28 |
+
ALLOWED_HOSTS = ["*"]
|
| 29 |
+
|
| 30 |
+
INSTALLED_APPS = [
|
| 31 |
+
'django.contrib.admin',
|
| 32 |
+
'django.contrib.auth',
|
| 33 |
+
'django.contrib.contenttypes',
|
| 34 |
+
'django.contrib.sessions',
|
| 35 |
+
'django.contrib.messages',
|
| 36 |
+
'django.contrib.staticfiles',
|
| 37 |
+
'webapp',
|
| 38 |
+
'django_browser_reload',
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
MIDDLEWARE = [
|
| 42 |
+
'django.middleware.security.SecurityMiddleware',
|
| 43 |
+
'django.contrib.sessions.middleware.SessionMiddleware',
|
| 44 |
+
'django.middleware.common.CommonMiddleware',
|
| 45 |
+
'django.middleware.csrf.CsrfViewMiddleware', # <-- ON
|
| 46 |
+
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
| 47 |
+
'django.contrib.messages.middleware.MessageMiddleware',
|
| 48 |
+
# you *can* keep clickjacking protection off if you really need iframes:
|
| 49 |
+
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
| 50 |
+
'django_browser_reload.middleware.BrowserReloadMiddleware',
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
CSRF_TRUSTED_ORIGINS = [
|
| 54 |
+
"https://peaceabolisher-ml-lab.hf.space",
|
| 55 |
+
"https://huggingface.co",
|
| 56 |
+
"https://*.huggingface.co",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
X_FRAME_OPTIONS = "ALLOWALL"
|
| 60 |
+
|
| 61 |
+
ROOT_URLCONF = 'myproject.urls'
|
| 62 |
+
|
| 63 |
+
TEMPLATES = [
|
| 64 |
+
{
|
| 65 |
+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
| 66 |
+
'DIRS': [],
|
| 67 |
+
'APP_DIRS': True,
|
| 68 |
+
'OPTIONS': {
|
| 69 |
+
'context_processors': [
|
| 70 |
+
'django.template.context_processors.request',
|
| 71 |
+
'django.contrib.auth.context_processors.auth',
|
| 72 |
+
'django.contrib.messages.context_processors.messages',
|
| 73 |
+
],
|
| 74 |
+
},
|
| 75 |
+
},
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
WSGI_APPLICATION = 'myproject.wsgi.application'
|
| 79 |
+
|
| 80 |
+
DATABASES = {
|
| 81 |
+
'default': {
|
| 82 |
+
'ENGINE': 'django.db.backends.sqlite3',
|
| 83 |
+
'NAME': BASE_DIR / 'db.sqlite3',
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
MEDIA_ROOT = BASE_DIR / "media"
|
| 88 |
+
MEDIA_URL = "/media/"
|
| 89 |
+
|
| 90 |
+
AUTH_PASSWORD_VALIDATORS = [
|
| 91 |
+
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
|
| 92 |
+
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
|
| 93 |
+
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
|
| 94 |
+
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
LANGUAGE_CODE = 'en-us'
|
| 98 |
+
TIME_ZONE = 'UTC'
|
| 99 |
+
USE_I18N = True
|
| 100 |
+
USE_TZ = True
|
| 101 |
+
|
| 102 |
+
STATIC_URL = 'static/'
|
| 103 |
+
STATIC_ROOT = BASE_DIR / "staticfiles"
|
| 104 |
+
|
| 105 |
+
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
myproject/urls.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# myproject/urls.py
|
| 2 |
+
from django.contrib import admin
|
| 3 |
+
from django.urls import path, include
|
| 4 |
+
from django.conf import settings
|
| 5 |
+
from django.conf.urls.static import static
|
| 6 |
+
|
| 7 |
+
urlpatterns = [
|
| 8 |
+
path('admin/', admin.site.urls),
|
| 9 |
+
# Include all URL patterns from the 'webapp' app
|
| 10 |
+
path('', include('webapp.urls')),
|
| 11 |
+
# Include django_browser_reload URLs if you're using it
|
| 12 |
+
path("__reload__/", include("django_browser_reload.urls")),
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
if settings.DEBUG:
|
| 16 |
+
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
myproject/wsgi.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
WSGI config for myproject project.
|
| 3 |
+
|
| 4 |
+
It exposes the WSGI callable as a module-level variable named ``application``.
|
| 5 |
+
|
| 6 |
+
For more information on this file, see
|
| 7 |
+
https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
from django.core.wsgi import get_wsgi_application
|
| 13 |
+
|
| 14 |
+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
| 15 |
+
|
| 16 |
+
application = get_wsgi_application()
|
requirements.txt
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Django
|
| 2 |
+
django-browser-reload
|
| 3 |
+
gunicorn
|
| 4 |
+
|
| 5 |
+
numpy
|
| 6 |
+
pandas
|
| 7 |
+
scikit-learn
|
| 8 |
+
xgboost
|
| 9 |
+
|
| 10 |
+
matplotlib
|
| 11 |
+
seaborn
|
| 12 |
+
|
| 13 |
+
shap
|
| 14 |
+
|
| 15 |
+
requests
|
| 16 |
+
python-dateutil
|
| 17 |
+
pytz
|
| 18 |
+
tzdata
|
| 19 |
+
PyYAML
|
| 20 |
+
imbalanced-learn
|
| 21 |
+
ctgan
|
| 22 |
+
tensorflow
|
| 23 |
+
scikeras
|
| 24 |
+
|
staticfiles/.gitkeep
ADDED
|
File without changes
|
webapp/__init__.py
ADDED
|
File without changes
|
webapp/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (191 Bytes). View file
|
|
|
webapp/__pycache__/admin.cpython-312.pyc
ADDED
|
Binary file (466 Bytes). View file
|
|
|
webapp/__pycache__/apps.cpython-312.pyc
ADDED
|
Binary file (497 Bytes). View file
|
|
|
webapp/__pycache__/forms.cpython-312.pyc
ADDED
|
Binary file (6.01 kB). View file
|
|
|
webapp/__pycache__/models.cpython-312.pyc
ADDED
|
Binary file (3.51 kB). View file
|
|
|
webapp/__pycache__/urls.cpython-312.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
webapp/__pycache__/views.cpython-312.pyc
ADDED
|
Binary file (26.1 kB). View file
|
|
|
webapp/admin.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/admin.py
|
| 2 |
+
from django.contrib import admin
|
| 3 |
+
from .models import SavedModel, PublicDataset
|
| 4 |
+
|
| 5 |
+
admin.site.register(SavedModel)
|
| 6 |
+
admin.site.register(PublicDataset)
|
webapp/apps.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.apps import AppConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class WebappConfig(AppConfig):
|
| 5 |
+
default_auto_field = 'django.db.models.BigAutoField'
|
| 6 |
+
name = 'webapp'
|
webapp/forms.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django import forms
|
| 2 |
+
from django.contrib.auth.forms import UserCreationForm
|
| 3 |
+
from django.contrib.auth import get_user_model
|
| 4 |
+
from .models import UserProfile
|
| 5 |
+
from datetime import date
|
| 6 |
+
|
| 7 |
+
SCALER_CHOICES = [
|
| 8 |
+
("standard", "Standard Scaler"),
|
| 9 |
+
("minmax", "MinMax Scaler"),
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
MODEL_CHOICES = [
|
| 13 |
+
("rf", "Random Forest"),
|
| 14 |
+
("svm", "Support Vector Machine"),
|
| 15 |
+
("knn", "K-Nearest Neighbors"),
|
| 16 |
+
("lr", "Logistic Regression"),
|
| 17 |
+
("gb", "Gradient Boosting"),
|
| 18 |
+
("xgb", "XGBoost"),
|
| 19 |
+
("mlp", "MLP (Neural Network)"),
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
META_CHOICES = [
|
| 23 |
+
("lr", "Logistic Regression"),
|
| 24 |
+
("rf", "Random Forest"),
|
| 25 |
+
("gb", "Gradient Boosting"),
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
ENSEMBLE_CHOICES = [
|
| 29 |
+
("none", "No Ensemble"),
|
| 30 |
+
("voting", "Voting Classifier"),
|
| 31 |
+
("stacking","Stacking Classifier"),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
VOTING_CHOICES = [
|
| 35 |
+
("hard", "Hard Voting"),
|
| 36 |
+
("soft", "Soft Voting"),
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
BALANCING_CHOICES = [
|
| 40 |
+
("none", "None"),
|
| 41 |
+
("over", "Random Oversampling"),
|
| 42 |
+
("smote", "SMOTE"),
|
| 43 |
+
("gans", "GANS"),
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
AUGMENT_CHOICES = [
|
| 47 |
+
("none", "None"),
|
| 48 |
+
("gans", "GANS"),
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class SaveModelForm(forms.Form):
|
| 53 |
+
name = forms.CharField(max_length=120)
|
| 54 |
+
public = forms.BooleanField(required=False)
|
| 55 |
+
description = forms.CharField(required=False,widget=forms.Textarea(attrs={"rows": 3, "maxlength": 2000})
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class UploadForm(forms.Form):
|
| 60 |
+
dataset = forms.FileField(
|
| 61 |
+
label="Upload CSV Dataset",
|
| 62 |
+
widget=forms.ClearableFileInput(attrs={"class": "form-control"})
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
scaler = forms.ChoiceField(
|
| 66 |
+
choices=SCALER_CHOICES,
|
| 67 |
+
initial="standard",
|
| 68 |
+
widget=forms.Select(attrs={"class": "form-select"})
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
base_models = forms.MultipleChoiceField(
|
| 72 |
+
choices=MODEL_CHOICES,
|
| 73 |
+
widget=forms.CheckboxSelectMultiple,
|
| 74 |
+
label="Base Models",
|
| 75 |
+
required=True,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
meta_learner = forms.ChoiceField(
|
| 79 |
+
choices=META_CHOICES,
|
| 80 |
+
initial="lr",
|
| 81 |
+
widget=forms.Select(attrs={"class": "form-select"})
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
ensemble_type = forms.ChoiceField(
|
| 85 |
+
choices=ENSEMBLE_CHOICES,
|
| 86 |
+
initial="none",
|
| 87 |
+
widget=forms.Select(attrs={"class": "form-select"})
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
voting_type = forms.ChoiceField(
|
| 91 |
+
choices=VOTING_CHOICES,
|
| 92 |
+
required=False,
|
| 93 |
+
initial="hard",
|
| 94 |
+
widget=forms.Select(attrs={"class": "form-select"})
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
balancing_strategy = forms.ChoiceField(
|
| 98 |
+
choices=BALANCING_CHOICES,
|
| 99 |
+
initial="none",
|
| 100 |
+
widget=forms.Select(attrs={"class": "form-select"})
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
augmentation = forms.ChoiceField(
|
| 104 |
+
choices=AUGMENT_CHOICES,
|
| 105 |
+
initial="none",
|
| 106 |
+
widget=forms.Select(attrs={"class": "form-select"})
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
target_samples = forms.IntegerField(
|
| 110 |
+
required=False,
|
| 111 |
+
min_value=1,
|
| 112 |
+
widget=forms.NumberInput(attrs={"class": "form-control", "placeholder": "e.g. 500"})
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def clean_base_models(self):
|
| 116 |
+
data = self.cleaned_data.get("base_models") or []
|
| 117 |
+
if len(data) == 0:
|
| 118 |
+
raise forms.ValidationError("Pick at least one base model.")
|
| 119 |
+
return data
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class RegisterForm(UserCreationForm):
|
| 123 |
+
full_name = forms.CharField(
|
| 124 |
+
max_length=150,
|
| 125 |
+
label="Name",
|
| 126 |
+
widget=forms.TextInput(attrs={"class": "form-control"})
|
| 127 |
+
)
|
| 128 |
+
date_of_birth = forms.DateField(
|
| 129 |
+
label="Date of birth",
|
| 130 |
+
widget=forms.DateInput(attrs={"type": "date", "class": "form-control"})
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
class Meta:
|
| 134 |
+
model = get_user_model()
|
| 135 |
+
fields = ("username", "full_name", "date_of_birth", "password1", "password2")
|
| 136 |
+
|
| 137 |
+
def clean_date_of_birth(self):
|
| 138 |
+
dob = self.cleaned_data["date_of_birth"]
|
| 139 |
+
if dob >= date.today():
|
| 140 |
+
raise forms.ValidationError("Date of birth must be in the past.")
|
| 141 |
+
return dob
|
| 142 |
+
|
| 143 |
+
def save(self, commit=True):
|
| 144 |
+
user = super().save(commit=False)
|
| 145 |
+
|
| 146 |
+
# Best-effort split full_name into first/last for the auth user
|
| 147 |
+
name = self.cleaned_data.get("full_name", "").strip()
|
| 148 |
+
first, *rest = name.split()
|
| 149 |
+
user.first_name = first or ""
|
| 150 |
+
user.last_name = " ".join(rest) if rest else ""
|
| 151 |
+
|
| 152 |
+
if commit:
|
| 153 |
+
user.save()
|
| 154 |
+
UserProfile.objects.create(
|
| 155 |
+
user=user,
|
| 156 |
+
full_name=name,
|
| 157 |
+
date_of_birth=self.cleaned_data["date_of_birth"],
|
| 158 |
+
)
|
| 159 |
+
return user
|
webapp/migrations/0001_initial.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by Django 5.2.3 on 2025-09-17 17:28
|
| 2 |
+
|
| 3 |
+
import django.db.models.deletion
|
| 4 |
+
import webapp.models
|
| 5 |
+
from django.conf import settings
|
| 6 |
+
from django.db import migrations, models
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Migration(migrations.Migration):
|
| 10 |
+
|
| 11 |
+
initial = True
|
| 12 |
+
|
| 13 |
+
dependencies = [
|
| 14 |
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
operations = [
|
| 18 |
+
migrations.CreateModel(
|
| 19 |
+
name='PublicDataset',
|
| 20 |
+
fields=[
|
| 21 |
+
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
| 22 |
+
('name', models.CharField(max_length=160)),
|
| 23 |
+
('description', models.TextField(blank=True)),
|
| 24 |
+
('file', models.FileField(upload_to=webapp.models.dataset_upload_path)),
|
| 25 |
+
('rows', models.IntegerField(blank=True, null=True)),
|
| 26 |
+
('cols', models.IntegerField(blank=True, null=True)),
|
| 27 |
+
('is_active', models.BooleanField(default=True)),
|
| 28 |
+
('created_at', models.DateTimeField(auto_now_add=True)),
|
| 29 |
+
],
|
| 30 |
+
),
|
| 31 |
+
migrations.CreateModel(
|
| 32 |
+
name='SavedModel',
|
| 33 |
+
fields=[
|
| 34 |
+
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
| 35 |
+
('name', models.CharField(max_length=120)),
|
| 36 |
+
('file', models.FileField(upload_to=webapp.models.model_upload_path)),
|
| 37 |
+
('public', models.BooleanField(default=False)),
|
| 38 |
+
('test_auc', models.FloatField(blank=True, null=True)),
|
| 39 |
+
('test_f1', models.FloatField(blank=True, null=True)),
|
| 40 |
+
('created_at', models.DateTimeField(auto_now_add=True)),
|
| 41 |
+
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='saved_models', to=settings.AUTH_USER_MODEL)),
|
| 42 |
+
],
|
| 43 |
+
),
|
| 44 |
+
]
|
webapp/migrations/0002_userprofile.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by Django 5.2.3 on 2025-09-25 10:28
|
| 2 |
+
|
| 3 |
+
import django.db.models.deletion
|
| 4 |
+
from django.conf import settings
|
| 5 |
+
from django.db import migrations, models
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Migration(migrations.Migration):
|
| 9 |
+
|
| 10 |
+
dependencies = [
|
| 11 |
+
('webapp', '0001_initial'),
|
| 12 |
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
operations = [
|
| 16 |
+
migrations.CreateModel(
|
| 17 |
+
name='UserProfile',
|
| 18 |
+
fields=[
|
| 19 |
+
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
| 20 |
+
('full_name', models.CharField(max_length=150)),
|
| 21 |
+
('date_of_birth', models.DateField()),
|
| 22 |
+
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
|
| 23 |
+
],
|
| 24 |
+
),
|
| 25 |
+
]
|
webapp/migrations/0003_savedmodel_description.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by Django 5.2.3 on 2025-11-04 10:45
|
| 2 |
+
|
| 3 |
+
from django.db import migrations, models
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Migration(migrations.Migration):
|
| 7 |
+
|
| 8 |
+
dependencies = [
|
| 9 |
+
('webapp', '0002_userprofile'),
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
operations = [
|
| 13 |
+
migrations.AddField(
|
| 14 |
+
model_name='savedmodel',
|
| 15 |
+
name='description',
|
| 16 |
+
field=models.TextField(blank=True, max_length=2000),
|
| 17 |
+
),
|
| 18 |
+
]
|
webapp/migrations/0004_savedmodel_trained_on.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by Django 5.2.3 on 2025-11-04 11:21
|
| 2 |
+
|
| 3 |
+
from django.db import migrations, models
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Migration(migrations.Migration):
|
| 7 |
+
|
| 8 |
+
dependencies = [
|
| 9 |
+
('webapp', '0003_savedmodel_description'),
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
operations = [
|
| 13 |
+
migrations.AddField(
|
| 14 |
+
model_name='savedmodel',
|
| 15 |
+
name='trained_on',
|
| 16 |
+
field=models.CharField(blank=True, max_length=200),
|
| 17 |
+
),
|
| 18 |
+
]
|
webapp/migrations/0005_add_trained_on_field.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by Django 5.2.3 on 2025-11-04 11:33
|
| 2 |
+
|
| 3 |
+
from django.db import migrations
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Migration(migrations.Migration):
|
| 7 |
+
|
| 8 |
+
dependencies = [
|
| 9 |
+
('webapp', '0004_savedmodel_trained_on'),
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
operations = [
|
| 13 |
+
]
|
webapp/migrations/__init__.py
ADDED
|
File without changes
|
webapp/migrations/__pycache__/0001_initial.cpython-312.pyc
ADDED
|
Binary file (2.75 kB). View file
|
|
|
webapp/migrations/__pycache__/0002_userprofile.cpython-312.pyc
ADDED
|
Binary file (1.53 kB). View file
|
|
|
webapp/migrations/__pycache__/0003_savedmodel_description.cpython-312.pyc
ADDED
|
Binary file (799 Bytes). View file
|
|
|
webapp/migrations/__pycache__/0004_savedmodel_trained_on.cpython-312.pyc
ADDED
|
Binary file (808 Bytes). View file
|
|
|
webapp/migrations/__pycache__/0005_add_trained_on_field.cpython-312.pyc
ADDED
|
Binary file (562 Bytes). View file
|
|
|
webapp/migrations/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (202 Bytes). View file
|
|
|
webapp/models.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/models.py
|
| 2 |
+
from django.db import models
|
| 3 |
+
from django.contrib.auth import get_user_model
|
| 4 |
+
|
| 5 |
+
User = get_user_model()
|
| 6 |
+
|
| 7 |
+
def model_upload_path(instance, filename):
|
| 8 |
+
return f"saved_models/{instance.owner_id}/{filename}"
|
| 9 |
+
|
| 10 |
+
def dataset_upload_path(instance, filename):
|
| 11 |
+
return f"public_datasets/{filename}"
|
| 12 |
+
|
| 13 |
+
class SavedModel(models.Model):
|
| 14 |
+
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="saved_models")
|
| 15 |
+
name = models.CharField(max_length=120)
|
| 16 |
+
description = models.TextField(blank=True, max_length=2000)
|
| 17 |
+
trained_on = models.CharField(max_length=200, blank=True)
|
| 18 |
+
file = models.FileField(upload_to=model_upload_path)
|
| 19 |
+
public = models.BooleanField(default=False)
|
| 20 |
+
test_auc = models.FloatField(null=True, blank=True)
|
| 21 |
+
test_f1 = models.FloatField(null=True, blank=True)
|
| 22 |
+
created_at = models.DateTimeField(auto_now_add=True)
|
| 23 |
+
|
| 24 |
+
def __str__(self):
|
| 25 |
+
return self.name
|
| 26 |
+
|
| 27 |
+
class PublicDataset(models.Model):
|
| 28 |
+
name = models.CharField(max_length=160)
|
| 29 |
+
description = models.TextField(blank=True)
|
| 30 |
+
file = models.FileField(upload_to=dataset_upload_path)
|
| 31 |
+
rows = models.IntegerField(null=True, blank=True)
|
| 32 |
+
cols = models.IntegerField(null=True, blank=True)
|
| 33 |
+
is_active = models.BooleanField(default=True)
|
| 34 |
+
created_at = models.DateTimeField(auto_now_add=True)
|
| 35 |
+
|
| 36 |
+
def __str__(self):
|
| 37 |
+
return self.name
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class UserProfile(models.Model):
|
| 41 |
+
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
|
| 42 |
+
full_name = models.CharField(max_length=150)
|
| 43 |
+
date_of_birth = models.DateField()
|
| 44 |
+
|
| 45 |
+
def __str__(self):
|
| 46 |
+
return f"{self.full_name} ({self.user.username})"
|
webapp/services/__init__.py
ADDED
|
File without changes
|
webapp/services/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (200 Bytes). View file
|
|
|
webapp/services/__pycache__/charts.cpython-312.pyc
ADDED
|
Binary file (1.68 kB). View file
|
|
|
webapp/services/__pycache__/inference.cpython-312.pyc
ADDED
|
Binary file (16.4 kB). View file
|
|
|
webapp/services/__pycache__/io_utils.cpython-312.pyc
ADDED
|
Binary file (1.4 kB). View file
|
|
|
webapp/services/__pycache__/ml_utils.cpython-312.pyc
ADDED
|
Binary file (5.35 kB). View file
|
|
|
webapp/services/__pycache__/training.cpython-312.pyc
ADDED
|
Binary file (40.7 kB). View file
|
|
|
webapp/services/charts.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/services/charts.py
|
| 2 |
+
import io, base64
|
| 3 |
+
import matplotlib
|
| 4 |
+
matplotlib.use('Agg')
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def preds_hist_data_url(preds) -> str:
|
| 9 |
+
buf = io.BytesIO()
|
| 10 |
+
plt.figure(figsize=(6,4))
|
| 11 |
+
try:
|
| 12 |
+
plt.hist(preds, bins=3)
|
| 13 |
+
except Exception:
|
| 14 |
+
vals, counts = np.unique(preds, return_counts=True)
|
| 15 |
+
plt.bar([str(v) for v in vals], counts)
|
| 16 |
+
plt.title('Predictions')
|
| 17 |
+
plt.tight_layout()
|
| 18 |
+
plt.savefig(buf, format='png')
|
| 19 |
+
plt.close()
|
| 20 |
+
buf.seek(0)
|
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
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io, os, uuid
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 6 |
+
import re
|
| 7 |
+
import joblib
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from django.conf import settings
|
| 11 |
+
from sklearn.metrics import f1_score, roc_auc_score
|
| 12 |
+
from sklearn.inspection import permutation_importance
|
| 13 |
+
|
| 14 |
+
import matplotlib
|
| 15 |
+
matplotlib.use("Agg")
|
| 16 |
+
import matplotlib.pyplot as plt
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
import shap
|
| 20 |
+
_SHAP_OK = True
|
| 21 |
+
except Exception:
|
| 22 |
+
_SHAP_OK = False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class InferenceResult:
|
| 27 |
+
error: Optional[str] = None
|
| 28 |
+
predictions: Optional[List[Tuple[str, int]]] = None
|
| 29 |
+
test_f1: Optional[float] = None
|
| 30 |
+
test_auc: Optional[float] = None
|
| 31 |
+
val_f1: Optional[float] = None
|
| 32 |
+
val_auc: Optional[float] = None
|
| 33 |
+
shap_url: Optional[str] = None
|
| 34 |
+
explain_type: Optional[str] = None
|
| 35 |
+
summary: Optional[Dict[str, Any]] = None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _pretty_feature_names(names: List[str]) -> List[str]:
|
| 40 |
+
out = []
|
| 41 |
+
for n in names:
|
| 42 |
+
s = str(n)
|
| 43 |
+
# strip ColumnTransformer prefixes
|
| 44 |
+
s = re.sub(r'^(num|cat)_{1,2}', '', s)
|
| 45 |
+
out.append(s if len(s) <= 40 else s[:37] + '…')
|
| 46 |
+
return out
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _read_model(upload):
|
| 50 |
+
if hasattr(upload, "read"):
|
| 51 |
+
data = upload.read()
|
| 52 |
+
return joblib.load(io.BytesIO(data))
|
| 53 |
+
return joblib.load(upload)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _coerce_numeric(df: pd.DataFrame) -> pd.DataFrame:
|
| 57 |
+
out = df.copy()
|
| 58 |
+
for c in out.columns:
|
| 59 |
+
if out[c].dtype == object:
|
| 60 |
+
coerced = pd.to_numeric(out[c], errors="coerce")
|
| 61 |
+
if coerced.notna().sum() > 0:
|
| 62 |
+
out[c] = coerced
|
| 63 |
+
return out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _media_plot_paths(run_id: str, tag: str) -> Tuple[str, str]:
|
| 67 |
+
rel_dir = "inference_runs"
|
| 68 |
+
abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir)
|
| 69 |
+
os.makedirs(abs_dir, exist_ok=True)
|
| 70 |
+
abs_path = os.path.join(abs_dir, f"{run_id}_{tag}.svg") # ← SVG
|
| 71 |
+
url = settings.MEDIA_URL + f"{rel_dir}/{run_id}_{tag}.svg"
|
| 72 |
+
return abs_path, url
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _try_shap(model, X: pd.DataFrame, feature_names: List[str], run_id: str) -> Tuple[Optional[str], Optional[List[Tuple[str, float]]]]:
|
| 76 |
+
if not _SHAP_OK:
|
| 77 |
+
return None, None
|
| 78 |
+
try:
|
| 79 |
+
bg = X.sample(min(50, len(X)), random_state=0)
|
| 80 |
+
ev = X.sample(min(200, len(X)), random_state=1)
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
exp = shap.Explainer(model, bg)
|
| 84 |
+
sv = exp(ev)
|
| 85 |
+
shap.summary_plot(sv, features=ev, feature_names=feature_names, plot_type="bar", show=False)
|
| 86 |
+
# mean absolute shap per feature
|
| 87 |
+
vals = np.abs(sv.values).mean(0)
|
| 88 |
+
except Exception:
|
| 89 |
+
def _f(A):
|
| 90 |
+
df = pd.DataFrame(A, columns=feature_names)
|
| 91 |
+
if hasattr(model, "predict_proba"):
|
| 92 |
+
return model.predict_proba(df)[:, 1]
|
| 93 |
+
return model.predict(df)
|
| 94 |
+
kexp = shap.KernelExplainer(_f, bg)
|
| 95 |
+
sv = kexp.shap_values(ev, nsamples=100)
|
| 96 |
+
shap.summary_plot(sv, ev, feature_names=feature_names, plot_type="bar", show=False)
|
| 97 |
+
vals = np.abs(sv).mean(0) # kernel returns ndarray
|
| 98 |
+
|
| 99 |
+
plt.tight_layout()
|
| 100 |
+
plt.gcf().set_size_inches(8, 5) # ← baseline size
|
| 101 |
+
abs_path, url = _media_plot_paths(run_id, "shap")
|
| 102 |
+
plt.savefig(abs_path, format="svg", bbox_inches="tight")
|
| 103 |
+
plt.close()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
importances = [(str(f), float(v)) for f, v in zip(feature_names, vals)]
|
| 107 |
+
return url, importances
|
| 108 |
+
except Exception:
|
| 109 |
+
try: plt.close()
|
| 110 |
+
except Exception: pass
|
| 111 |
+
return None, None
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _try_perm(model, X: pd.DataFrame, y: pd.Series, feature_names: List[str], run_id: str) -> Tuple[Optional[str], Optional[List[Tuple[str, float]]]]:
|
| 116 |
+
try:
|
| 117 |
+
res = permutation_importance(model, X, y, n_repeats=10, random_state=0, scoring="roc_auc")
|
| 118 |
+
imps = pd.Series(res.importances_mean, index=feature_names).fillna(0.0)
|
| 119 |
+
top = imps.sort_values().tail(25)
|
| 120 |
+
|
| 121 |
+
plt.figure(figsize=(10, 6), dpi=140)
|
| 122 |
+
cols = ["tab:red" if v < 0 else "tab:green" for v in top.values]
|
| 123 |
+
plt.barh(top.index, top.values, color=cols, alpha=0.9)
|
| 124 |
+
plt.axvline(0, linestyle="--", linewidth=1, alpha=0.6)
|
| 125 |
+
plt.title("Permutation importance")
|
| 126 |
+
plt.xlabel("Δ ROC AUC when permuted")
|
| 127 |
+
plt.tight_layout()
|
| 128 |
+
|
| 129 |
+
abs_path, url = _media_plot_paths(run_id, "perm")
|
| 130 |
+
plt.savefig(abs_path, format="svg", bbox_inches="tight")
|
| 131 |
+
plt.close()
|
| 132 |
+
|
| 133 |
+
importances = [(str(f), float(s)) for f, s in zip(feature_names, res.importances_mean)]
|
| 134 |
+
return url, importances
|
| 135 |
+
except Exception:
|
| 136 |
+
try: plt.close()
|
| 137 |
+
except Exception: pass
|
| 138 |
+
return None, None
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _normalize_artifact(obj: Any) -> Dict[str, Any]:
|
| 142 |
+
"""
|
| 143 |
+
Normalize different saved shapes into a common dict:
|
| 144 |
+
keys: model, preprocessor|scaler (optional), selector (optional),
|
| 145 |
+
pre_features (optional), final_features (optional),
|
| 146 |
+
val_auc/val_f1/test_auc/test_f1 (optional)
|
| 147 |
+
"""
|
| 148 |
+
# A) New/modern artifact (dict with "model")
|
| 149 |
+
if isinstance(obj, dict) and "model" in obj:
|
| 150 |
+
return {
|
| 151 |
+
"model": obj["model"],
|
| 152 |
+
"preprocessor": obj.get("preprocessor"),
|
| 153 |
+
"scaler": obj.get("scaler"),
|
| 154 |
+
"selector": obj.get("selector"),
|
| 155 |
+
"pre_features": obj.get("pre_selection_feature_names"),
|
| 156 |
+
"final_features": obj.get("final_feature_names"),
|
| 157 |
+
"val_auc": obj.get("val_auc"),
|
| 158 |
+
"val_f1": obj.get("val_f1"),
|
| 159 |
+
"test_auc": obj.get("test_auc"),
|
| 160 |
+
"test_f1": obj.get("test_f1"),
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
# B) Older scripts (dict with model + scaler and possibly selector + feature lists)
|
| 164 |
+
if isinstance(obj, dict) and "model" in obj and ("scaler" in obj or "preprocessor" in obj):
|
| 165 |
+
return {
|
| 166 |
+
"model": obj["model"],
|
| 167 |
+
"preprocessor": obj.get("preprocessor"),
|
| 168 |
+
"scaler": obj.get("scaler"),
|
| 169 |
+
"selector": obj.get("selector"),
|
| 170 |
+
"pre_features": obj.get("pre_selection_feature_names"),
|
| 171 |
+
"final_features": obj.get("final_feature_names") or obj.get("feature_names"),
|
| 172 |
+
"val_auc": obj.get("val_auc"),
|
| 173 |
+
"val_f1": obj.get("val_f1"),
|
| 174 |
+
"test_auc": obj.get("test_auc"),
|
| 175 |
+
"test_f1": obj.get("test_f1"),
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
# C) Plain sklearn Pipeline or bare estimator
|
| 179 |
+
if hasattr(obj, "predict") and hasattr(obj, "fit"):
|
| 180 |
+
return {
|
| 181 |
+
"model": obj,
|
| 182 |
+
"preprocessor": None,
|
| 183 |
+
"scaler": None,
|
| 184 |
+
"selector": None,
|
| 185 |
+
"pre_features": None,
|
| 186 |
+
"final_features": list(getattr(obj, "feature_names_in_", [])) or None,
|
| 187 |
+
"val_auc": None, "val_f1": None, "test_auc": None, "test_f1": None,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
raise ValueError("Unrecognized model file format")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def run_inference(model_file, test_file) -> InferenceResult:
|
| 194 |
+
# Load model/artifact
|
| 195 |
+
try:
|
| 196 |
+
obj = _read_model(model_file)
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return InferenceResult(error=f"Could not load model file: {e}")
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
art = _normalize_artifact(obj)
|
| 202 |
+
except Exception as e:
|
| 203 |
+
return InferenceResult(error=f"Uploaded model file is not a recognized artifact: {e}")
|
| 204 |
+
|
| 205 |
+
# Load test CSV
|
| 206 |
+
try:
|
| 207 |
+
df = pd.read_csv(test_file) if hasattr(test_file, "read") else pd.read_csv(str(test_file))
|
| 208 |
+
except Exception as e:
|
| 209 |
+
return InferenceResult(error=f"Could not read test data: {e}")
|
| 210 |
+
|
| 211 |
+
y = df["healthy"].astype(int).reset_index(drop=True) if "healthy" in df.columns else None
|
| 212 |
+
X = df.drop(columns=["healthy"]) if "healthy" in df.columns else df
|
| 213 |
+
X = _coerce_numeric(X)
|
| 214 |
+
|
| 215 |
+
model = art["model"]
|
| 216 |
+
preprocessor = art.get("preprocessor")
|
| 217 |
+
scaler = art.get("scaler")
|
| 218 |
+
selector = art.get("selector")
|
| 219 |
+
pre_feats = art.get("pre_features")
|
| 220 |
+
final_feats = art.get("final_features")
|
| 221 |
+
|
| 222 |
+
# ── Preprocess (A: reindex to training columns before transform) ───────────
|
| 223 |
+
try:
|
| 224 |
+
if preprocessor is not None:
|
| 225 |
+
# Columns the ColumnTransformer saw during fit (raw, before OHE/scale)
|
| 226 |
+
raw_cols = list(getattr(preprocessor, "feature_names_in_", []))
|
| 227 |
+
if raw_cols:
|
| 228 |
+
# Drop extras like `sample_id`; add any missing cols as NaN for imputers
|
| 229 |
+
X_raw = X.reindex(columns=raw_cols, fill_value=np.nan)
|
| 230 |
+
else:
|
| 231 |
+
X_raw = X # fallback if sklearn version lacks feature_names_in_
|
| 232 |
+
Xp_arr = preprocessor.transform(X_raw)
|
| 233 |
+
names = preprocessor.get_feature_names_out().tolist()
|
| 234 |
+
Xp = pd.DataFrame(Xp_arr, columns=names).astype(np.float32)
|
| 235 |
+
|
| 236 |
+
elif scaler is not None:
|
| 237 |
+
# If an older artifact saved a bare scaler, align to its training columns too
|
| 238 |
+
raw_cols = list(getattr(scaler, "feature_names_in_", []))
|
| 239 |
+
X_raw = X.reindex(columns=raw_cols, fill_value=np.nan) if raw_cols else X
|
| 240 |
+
if not hasattr(scaler, "n_features_in_"):
|
| 241 |
+
try:
|
| 242 |
+
scaler.fit(X_raw)
|
| 243 |
+
except Exception:
|
| 244 |
+
pass
|
| 245 |
+
Xp = pd.DataFrame(scaler.transform(X_raw), columns=X_raw.columns).astype(np.float32)
|
| 246 |
+
|
| 247 |
+
else:
|
| 248 |
+
Xp = X.copy()
|
| 249 |
+
|
| 250 |
+
# Feature selection / alignment
|
| 251 |
+
if selector is not None and pre_feats is not None:
|
| 252 |
+
X_aligned = Xp.reindex(columns=pre_feats, fill_value=0.0)
|
| 253 |
+
X_final_arr = selector.transform(X_aligned)
|
| 254 |
+
Xf = pd.DataFrame(X_final_arr, columns=final_feats)
|
| 255 |
+
elif final_feats is not None:
|
| 256 |
+
Xf = Xp.reindex(columns=final_feats, fill_value=0.0)
|
| 257 |
+
elif hasattr(model, "feature_names_in_"):
|
| 258 |
+
needs = list(model.feature_names_in_)
|
| 259 |
+
Xf = Xp.reindex(columns=needs, fill_value=0.0)
|
| 260 |
+
final_feats = needs
|
| 261 |
+
else:
|
| 262 |
+
Xf = Xp
|
| 263 |
+
final_feats = Xf.columns.tolist()
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return InferenceResult(error=f"Preprocessing/feature selection failed: {e}")
|
| 266 |
+
|
| 267 |
+
# Clean labels for plots/links (drop num__/cat__ prefixes)
|
| 268 |
+
pretty_feats = _pretty_feature_names(final_feats)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# Predict
|
| 272 |
+
try:
|
| 273 |
+
y_pred = model.predict(Xf)
|
| 274 |
+
except Exception as e:
|
| 275 |
+
return InferenceResult(error=f"Model prediction failed: {e}")
|
| 276 |
+
|
| 277 |
+
# Metrics (optional)
|
| 278 |
+
test_f1 = test_auc = None
|
| 279 |
+
if y is not None and len(y) == len(y_pred):
|
| 280 |
+
try:
|
| 281 |
+
test_f1 = float(f1_score(y, y_pred))
|
| 282 |
+
except Exception:
|
| 283 |
+
test_f1 = None
|
| 284 |
+
try:
|
| 285 |
+
if hasattr(model, "predict_proba"):
|
| 286 |
+
test_auc = float(roc_auc_score(y, model.predict_proba(Xf)[:, 1]))
|
| 287 |
+
except Exception:
|
| 288 |
+
test_auc = None
|
| 289 |
+
|
| 290 |
+
# Explainability
|
| 291 |
+
run_id = uuid.uuid4().hex
|
| 292 |
+
summary = None
|
| 293 |
+
|
| 294 |
+
shap_url, shap_importances = _try_shap(model, Xf, pretty_feats, run_id)
|
| 295 |
+
explain_type = "shap" if shap_url else None
|
| 296 |
+
|
| 297 |
+
if shap_url:
|
| 298 |
+
summary = {"explain_type": "shap", "shap_importance": shap_importances}
|
| 299 |
+
elif y is not None:
|
| 300 |
+
perm_url, perm_importances = _try_perm(model, Xf, y, pretty_feats, run_id)
|
| 301 |
+
if perm_url:
|
| 302 |
+
shap_url = perm_url
|
| 303 |
+
explain_type = "permutation"
|
| 304 |
+
summary = {"explain_type": "permutation", "permutation_importance": perm_importances}
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# Preview (show sample_id if present)
|
| 308 |
+
n = min(25, len(df))
|
| 309 |
+
row_ids = (
|
| 310 |
+
df["sample_id"].astype(str).tolist()[:n]
|
| 311 |
+
if "sample_id" in df.columns else [str(i) for i in range(n)]
|
| 312 |
+
)
|
| 313 |
+
preds_head = list(zip(row_ids, [int(y_pred[i]) for i in range(n)]))
|
| 314 |
+
|
| 315 |
+
return InferenceResult(
|
| 316 |
+
error=None,
|
| 317 |
+
predictions=preds_head,
|
| 318 |
+
test_f1=test_f1,
|
| 319 |
+
test_auc=test_auc,
|
| 320 |
+
val_f1=(None if art.get("val_f1") is None else float(art["val_f1"])),
|
| 321 |
+
val_auc=(None if art.get("val_auc") is None else float(art["val_auc"])),
|
| 322 |
+
shap_url=shap_url,
|
| 323 |
+
explain_type=explain_type,
|
| 324 |
+
summary=summary, #make sure the new summary is returned
|
| 325 |
+
)
|
| 326 |
+
|
webapp/services/io_utils.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/services/io_utils.py
|
| 2 |
+
import io
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
def read_csv_or_txt(uploaded_file) -> pd.DataFrame:
|
| 6 |
+
"""Reads CSV or TXT. Ignores lines starting with #."""
|
| 7 |
+
if not uploaded_file:
|
| 8 |
+
raise ValueError("Missing file.")
|
| 9 |
+
raw = uploaded_file.read().decode("utf-8", errors="replace")
|
| 10 |
+
lines = raw.splitlines()
|
| 11 |
+
data_lines = [ln for ln in lines if not ln.strip().startswith("#")]
|
| 12 |
+
if not data_lines:
|
| 13 |
+
raise ValueError("No data rows found.")
|
| 14 |
+
txt = "\n".join(data_lines)
|
| 15 |
+
try:
|
| 16 |
+
return pd.read_csv(io.StringIO(txt)) # comma
|
| 17 |
+
except Exception:
|
| 18 |
+
return pd.read_csv(io.StringIO(txt), sep="\t") # tab
|
webapp/services/ml_utils.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/services/ml_utils.py
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import List, Optional, Tuple
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
from sklearn.compose import ColumnTransformer
|
| 8 |
+
from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder
|
| 9 |
+
from sklearn.pipeline import Pipeline
|
| 10 |
+
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier, StackingClassifier
|
| 11 |
+
from sklearn.linear_model import LogisticRegression
|
| 12 |
+
from sklearn.svm import SVC
|
| 13 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from xgboost import XGBClassifier
|
| 17 |
+
XGB_OK = True
|
| 18 |
+
except Exception:
|
| 19 |
+
XGB_OK = False
|
| 20 |
+
|
| 21 |
+
# Optional balancing
|
| 22 |
+
try:
|
| 23 |
+
from imblearn.over_sampling import RandomOverSampler, SMOTE
|
| 24 |
+
IMB_OK = True
|
| 25 |
+
except Exception:
|
| 26 |
+
IMB_OK = False
|
| 27 |
+
|
| 28 |
+
NON_FEATURE_COLS = {'healthy','label','target','sample_id','id'}
|
| 29 |
+
|
| 30 |
+
def get_model_from_choice(choice: str):
|
| 31 |
+
if choice == 'rf':
|
| 32 |
+
return RandomForestClassifier()
|
| 33 |
+
if choice == 'svm':
|
| 34 |
+
return SVC(probability=True)
|
| 35 |
+
if choice == 'knn':
|
| 36 |
+
return KNeighborsClassifier()
|
| 37 |
+
if choice == 'lr':
|
| 38 |
+
return LogisticRegression(max_iter=1000)
|
| 39 |
+
if choice == 'gb':
|
| 40 |
+
return GradientBoostingClassifier()
|
| 41 |
+
if choice == 'xgb' and XGB_OK:
|
| 42 |
+
return XGBClassifier(use_label_encoder=False, eval_metric='logloss')
|
| 43 |
+
if choice == 'mlp':
|
| 44 |
+
from sklearn.neural_network import MLPClassifier
|
| 45 |
+
return MLPClassifier(hidden_layer_sizes=(128,64), max_iter=500)
|
| 46 |
+
raise ValueError(f"Unsupported model choice: {choice}")
|
| 47 |
+
|
| 48 |
+
def build_preprocessor(scaler_key: str, X: pd.DataFrame) -> ColumnTransformer:
|
| 49 |
+
num_cols = X.select_dtypes(include='number').columns.tolist()
|
| 50 |
+
cat_cols = X.select_dtypes(exclude='number').columns.tolist()
|
| 51 |
+
|
| 52 |
+
scaler = StandardScaler() if scaler_key == 'standard' else MinMaxScaler()
|
| 53 |
+
return ColumnTransformer(
|
| 54 |
+
transformers=[
|
| 55 |
+
('num', scaler, num_cols),
|
| 56 |
+
('cat', OneHotEncoder(handle_unknown='ignore', sparse_output=False), cat_cols),
|
| 57 |
+
],
|
| 58 |
+
remainder='drop',
|
| 59 |
+
verbose_feature_names_out=False,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def build_estimator(base_models: List[str], meta_learner: str,
|
| 63 |
+
ensemble_type: str, voting_type: str):
|
| 64 |
+
estimators = [(k, get_model_from_choice(k)) for k in base_models]
|
| 65 |
+
if len(estimators) == 0:
|
| 66 |
+
raise ValueError("Select at least one base model.")
|
| 67 |
+
if len(estimators) >= 2 and ensemble_type == 'none':
|
| 68 |
+
ensemble_type = 'stacking' # server-side guard
|
| 69 |
+
|
| 70 |
+
if ensemble_type == 'voting':
|
| 71 |
+
return VotingClassifier(estimators=estimators, voting=voting_type)
|
| 72 |
+
if ensemble_type == 'stacking':
|
| 73 |
+
meta = get_model_from_choice(meta_learner)
|
| 74 |
+
return StackingClassifier(estimators=estimators, final_estimator=meta)
|
| 75 |
+
return estimators[0][1]
|
| 76 |
+
|
| 77 |
+
def apply_balancing(X: pd.DataFrame, y: pd.Series,
|
| 78 |
+
strategy: str, target_samples: Optional[int]) -> Tuple[pd.DataFrame, pd.Series]:
|
| 79 |
+
"""Applies optional balancing. SMOTE/oversampling via imblearn; GAN hooks left for you to plug in."""
|
| 80 |
+
if strategy == 'none':
|
| 81 |
+
return X, y
|
| 82 |
+
if strategy == 'over':
|
| 83 |
+
if not IMB_OK:
|
| 84 |
+
raise RuntimeError("imblearn not installed for RandomOverSampler.")
|
| 85 |
+
ros = RandomOverSampler()
|
| 86 |
+
Xr, yr = ros.fit_resample(X, y)
|
| 87 |
+
return Xr, yr
|
| 88 |
+
if strategy == 'smote':
|
| 89 |
+
if not IMB_OK:
|
| 90 |
+
raise RuntimeError("imblearn not installed for SMOTE.")
|
| 91 |
+
sm = SMOTE()
|
| 92 |
+
Xr, yr = sm.fit_resample(X, y)
|
| 93 |
+
return Xr, yr
|
| 94 |
+
if strategy == 'gans':
|
| 95 |
+
# 🔌 hook your GAN generator here; placeholder pass-through:
|
| 96 |
+
# from your_module import synthesize_with_gan
|
| 97 |
+
# Xr, yr = synthesize_with_gan(X, y, target_samples=target_samples)
|
| 98 |
+
return X, y # no-op by default
|
| 99 |
+
return X, y
|
| 100 |
+
|
| 101 |
+
def apply_augmentation(X_train: pd.DataFrame, y_train: pd.Series,
|
| 102 |
+
augmentation: str, target_samples: Optional[int]) -> Tuple[pd.DataFrame, pd.Series]:
|
| 103 |
+
if augmentation == 'none':
|
| 104 |
+
return X_train, y_train
|
| 105 |
+
if augmentation == 'gans':
|
| 106 |
+
# 🔌 hook GAN augmentation for the training fold only
|
| 107 |
+
return X_train, y_train # no-op by default
|
| 108 |
+
return X_train, y_train
|
webapp/services/testing.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/services/testing.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import io
|
| 4 |
+
from typing import Dict, Any, Tuple, Optional
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import joblib
|
| 8 |
+
from sklearn.metrics import f1_score, roc_auc_score, accuracy_score, confusion_matrix
|
| 9 |
+
|
| 10 |
+
NON_FEATURE_COLS = {"healthy", "label", "target", "sample_id", "id"}
|
| 11 |
+
|
| 12 |
+
def _read_txt_like(uploaded_file) -> pd.DataFrame:
|
| 13 |
+
raw = uploaded_file.read().decode("utf-8", errors="replace")
|
| 14 |
+
lines = [ln for ln in raw.splitlines() if not ln.strip().startswith("#")]
|
| 15 |
+
if not lines:
|
| 16 |
+
raise ValueError("No data rows found (file only contains comments).")
|
| 17 |
+
txt = "\n".join(lines)
|
| 18 |
+
try:
|
| 19 |
+
df = pd.read_csv(io.StringIO(txt))
|
| 20 |
+
except Exception:
|
| 21 |
+
df = pd.read_csv(io.StringIO(txt), sep="\t")
|
| 22 |
+
if df.empty:
|
| 23 |
+
raise ValueError("Parsed an empty table. Check delimiter and header.")
|
| 24 |
+
return df
|
| 25 |
+
|
| 26 |
+
def _align_numeric(df: pd.DataFrame) -> pd.DataFrame:
|
| 27 |
+
X = df.drop(columns=[c for c in NON_FEATURE_COLS if c in df.columns], errors="ignore").copy()
|
| 28 |
+
for c in X.columns:
|
| 29 |
+
X[c] = pd.to_numeric(X[c], errors="coerce").fillna(0.0)
|
| 30 |
+
return X
|
| 31 |
+
|
| 32 |
+
def _load_artifact(model_file) -> Dict[str, Any]:
|
| 33 |
+
art = joblib.load(model_file)
|
| 34 |
+
for k in ["model","scaler","final_feature_names","pre_selection_feature_names"]:
|
| 35 |
+
if k not in art:
|
| 36 |
+
raise ValueError(f"Model artifact is missing '{k}'.")
|
| 37 |
+
return art
|
| 38 |
+
|
| 39 |
+
def _transform_like_training(art: Dict[str, Any], X_raw: pd.DataFrame) -> pd.DataFrame:
|
| 40 |
+
# 1) align to pre-selection space
|
| 41 |
+
X_pre = X_raw.reindex(columns=art["pre_selection_feature_names"], fill_value=0.0)
|
| 42 |
+
# 2) scale with training scaler
|
| 43 |
+
X_scaled = art["scaler"].transform(X_pre)
|
| 44 |
+
X_scaled = pd.DataFrame(X_scaled, columns=art["pre_selection_feature_names"]).astype(np.float32)
|
| 45 |
+
# 3) feature selection
|
| 46 |
+
if art.get("selector") is not None:
|
| 47 |
+
X_sel_arr = art["selector"].transform(X_scaled)
|
| 48 |
+
X_sel = pd.DataFrame(X_sel_arr, columns=art["final_feature_names"])
|
| 49 |
+
else:
|
| 50 |
+
X_sel = X_scaled[art["final_feature_names"]]
|
| 51 |
+
return X_sel
|
| 52 |
+
|
| 53 |
+
def run_inference(model_file, test_file) -> Tuple[np.ndarray, Dict[str, Any]]:
|
| 54 |
+
"""Unlabeled data → predictions."""
|
| 55 |
+
art = _load_artifact(model_file)
|
| 56 |
+
df = _read_txt_like(test_file)
|
| 57 |
+
X = _align_numeric(df)
|
| 58 |
+
X_sel = _transform_like_training(art, X)
|
| 59 |
+
preds = art["model"].predict(X_sel)
|
| 60 |
+
meta = {
|
| 61 |
+
"scaler_type": art.get("scaler_type"),
|
| 62 |
+
"feature_method": art.get("feature_method"),
|
| 63 |
+
"k": art.get("k"),
|
| 64 |
+
"ensemble_type": art.get("ensemble_type"),
|
| 65 |
+
"base_models": art.get("base_models"),
|
| 66 |
+
"meta_learner": art.get("meta_learner"),
|
| 67 |
+
"voting_type": art.get("voting_type"),
|
| 68 |
+
"balancing_method": art.get("balancing_method"),
|
| 69 |
+
"augmentation": art.get("augmentation"),
|
| 70 |
+
}
|
| 71 |
+
return preds, meta
|
| 72 |
+
|
| 73 |
+
def evaluate(model_file, labeled_test_file) -> Tuple[Dict[str, Any], np.ndarray, Dict[str, Any]]:
|
| 74 |
+
"""
|
| 75 |
+
Labeled data with a 'healthy' column → metrics + predictions.
|
| 76 |
+
"""
|
| 77 |
+
art = _load_artifact(model_file)
|
| 78 |
+
df = _read_txt_like(labeled_test_file)
|
| 79 |
+
if "healthy" not in df.columns:
|
| 80 |
+
raise ValueError("Evaluation requires a 'healthy' column in the uploaded file.")
|
| 81 |
+
y_true = df["healthy"].astype(int).values
|
| 82 |
+
X = _align_numeric(df)
|
| 83 |
+
X_sel = _transform_like_training(art, X)
|
| 84 |
+
model = art["model"]
|
| 85 |
+
|
| 86 |
+
y_pred = model.predict(X_sel)
|
| 87 |
+
|
| 88 |
+
# Probabilities for AUC if available
|
| 89 |
+
auc = None
|
| 90 |
+
if hasattr(model, "predict_proba"):
|
| 91 |
+
try:
|
| 92 |
+
y_prob = model.predict_proba(X_sel)[:, 1]
|
| 93 |
+
auc = roc_auc_score(y_true, y_prob)
|
| 94 |
+
except ValueError:
|
| 95 |
+
auc = None
|
| 96 |
+
|
| 97 |
+
acc = accuracy_score(y_true, y_pred)
|
| 98 |
+
f1 = f1_score(y_true, y_pred)
|
| 99 |
+
cm = confusion_matrix(y_true, y_pred).tolist()
|
| 100 |
+
|
| 101 |
+
metrics = {"accuracy": acc, "f1": f1, "auc": auc, "confusion_matrix": cm}
|
| 102 |
+
meta = {
|
| 103 |
+
"scaler_type": art.get("scaler_type"),
|
| 104 |
+
"feature_method": art.get("feature_method"),
|
| 105 |
+
"k": art.get("k"),
|
| 106 |
+
"ensemble_type": art.get("ensemble_type"),
|
| 107 |
+
"base_models": art.get("base_models"),
|
| 108 |
+
"meta_learner": art.get("meta_learner"),
|
| 109 |
+
"voting_type": art.get("voting_type"),
|
| 110 |
+
"balancing_method": art.get("balancing_method"),
|
| 111 |
+
"augmentation": art.get("augmentation"),
|
| 112 |
+
}
|
| 113 |
+
return metrics, y_pred, meta
|
| 114 |
+
|
| 115 |
+
def auto_test(model_file, test_file) -> Dict[str, Any]:
|
| 116 |
+
"""
|
| 117 |
+
Convenience: if file has 'healthy', run evaluate(); otherwise run_inference().
|
| 118 |
+
Views can call only this and stay skinny.
|
| 119 |
+
"""
|
| 120 |
+
# We need to read once to detect label, then rewind for the actual loader.
|
| 121 |
+
# Duplicate the file object using bytes to reuse:
|
| 122 |
+
raw = test_file.read()
|
| 123 |
+
buf1 = io.BytesIO(raw)
|
| 124 |
+
buf2 = io.BytesIO(raw)
|
| 125 |
+
|
| 126 |
+
df_probe = _read_txt_like(buf1)
|
| 127 |
+
if "healthy" in df_probe.columns:
|
| 128 |
+
metrics, preds, meta = evaluate(model_file, buf2)
|
| 129 |
+
return {"metrics": metrics, "preds": preds, "meta": meta, "labeled": True}
|
| 130 |
+
else:
|
| 131 |
+
preds, meta = run_inference(model_file, buf2)
|
| 132 |
+
return {"metrics": None, "preds": preds, "meta": meta, "labeled": False}
|
webapp/services/training.py
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# webapp/services/training.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import copy
|
| 4 |
+
import os
|
| 5 |
+
import uuid
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 8 |
+
import joblib
|
| 9 |
+
import matplotlib
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import numpy as np
|
| 12 |
+
import re
|
| 13 |
+
import pandas as pd
|
| 14 |
+
from typing import Callable
|
| 15 |
+
from django.conf import settings
|
| 16 |
+
from sklearn.base import clone
|
| 17 |
+
from sklearn.compose import ColumnTransformer
|
| 18 |
+
from sklearn.ensemble import (
|
| 19 |
+
GradientBoostingClassifier,
|
| 20 |
+
RandomForestClassifier,
|
| 21 |
+
StackingClassifier,
|
| 22 |
+
VotingClassifier,
|
| 23 |
+
)
|
| 24 |
+
from sklearn.feature_selection import RFECV, SelectKBest, mutual_info_classif
|
| 25 |
+
from sklearn.inspection import permutation_importance
|
| 26 |
+
from sklearn.linear_model import LogisticRegression
|
| 27 |
+
from sklearn.metrics import f1_score, roc_auc_score
|
| 28 |
+
from sklearn.model_selection import GridSearchCV, train_test_split
|
| 29 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 30 |
+
from sklearn.pipeline import Pipeline
|
| 31 |
+
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder, StandardScaler
|
| 32 |
+
from sklearn.svm import SVC
|
| 33 |
+
|
| 34 |
+
# ------------------------------------------------------------------------------
|
| 35 |
+
# Optional dependencies (best-effort; gracefully degrade if missing)
|
| 36 |
+
# ------------------------------------------------------------------------------
|
| 37 |
+
try:
|
| 38 |
+
from xgboost import XGBClassifier
|
| 39 |
+
_XGB_OK = True
|
| 40 |
+
except Exception:
|
| 41 |
+
_XGB_OK = False
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
# Try (ctgan >= 0.6)
|
| 45 |
+
from ctgan import CTGAN as _CTGANClass
|
| 46 |
+
_CTGAN_OK = True
|
| 47 |
+
except Exception:
|
| 48 |
+
try:
|
| 49 |
+
# Fallback for very old ctgan (< 0.6)
|
| 50 |
+
from ctgan import CTGANSynthesizer as _CTGANClass
|
| 51 |
+
_CTGAN_OK = True
|
| 52 |
+
except Exception:
|
| 53 |
+
_CTGAN_OK = False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
import shap
|
| 58 |
+
_SHAP_OK = True
|
| 59 |
+
except Exception:
|
| 60 |
+
_SHAP_OK = False
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
from scikeras.wrappers import KerasClassifier
|
| 64 |
+
import tensorflow as tf
|
| 65 |
+
from tensorflow.keras import Input
|
| 66 |
+
from tensorflow.keras.layers import Dense, Dropout
|
| 67 |
+
from tensorflow.keras.models import Sequential
|
| 68 |
+
from tensorflow.keras.optimizers import Adam
|
| 69 |
+
_MLP_OK = True
|
| 70 |
+
except Exception:
|
| 71 |
+
_MLP_OK = False
|
| 72 |
+
|
| 73 |
+
# Matplotlib backend for headless servers
|
| 74 |
+
matplotlib.use("Agg")
|
| 75 |
+
|
| 76 |
+
# ------------------------------------------------------------------------------
|
| 77 |
+
# Data structures
|
| 78 |
+
# ------------------------------------------------------------------------------
|
| 79 |
+
@dataclass
|
| 80 |
+
class TrainOptions:
|
| 81 |
+
scaler: str # 'standard' | 'minmax'
|
| 82 |
+
base_models: List[str] # e.g. ['rf','svm',...]
|
| 83 |
+
ensemble_type: str # 'none' | 'voting' | 'stacking'
|
| 84 |
+
meta_learner: Optional[str] = None # 'lr' | 'rf' | 'gb' (for stacking)
|
| 85 |
+
voting_type: Optional[str] = None # 'hard' | 'soft' (for voting)
|
| 86 |
+
balancing: str = "none" # 'none' | 'over' | 'smote' | 'gans'
|
| 87 |
+
augmentation: str = "none" # 'none' | 'gans'
|
| 88 |
+
target_samples: Optional[int] = None # for augmentation == 'gans'
|
| 89 |
+
random_state: int = 42
|
| 90 |
+
test_size: float = 0.2
|
| 91 |
+
val_size: float = 0.25
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@dataclass
|
| 95 |
+
class TrainResult:
|
| 96 |
+
val_auc: Optional[float]
|
| 97 |
+
val_f1: float
|
| 98 |
+
test_auc: Optional[float]
|
| 99 |
+
test_f1: float
|
| 100 |
+
summary: Dict[str, Any]
|
| 101 |
+
model_path: Optional[str]
|
| 102 |
+
artifact: Dict[str, Any]
|
| 103 |
+
shap_relpath: Optional[str] = None # (may point to SHAP or permutation plot)
|
| 104 |
+
|
| 105 |
+
# ------------------------------------------------------------------------------
|
| 106 |
+
# Model registry & small helpers
|
| 107 |
+
# ------------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
# --- JSON-safe helpers (put after imports) ---
|
| 110 |
+
# --- JSON-safe helpers ---
|
| 111 |
+
def _to_py_scalar(x):
|
| 112 |
+
if isinstance(x, (np.integer,)):
|
| 113 |
+
return int(x)
|
| 114 |
+
if isinstance(x, (np.floating,)):
|
| 115 |
+
return float(x)
|
| 116 |
+
if isinstance(x, (np.bool_,)):
|
| 117 |
+
return bool(x)
|
| 118 |
+
if isinstance(x, (np.ndarray,)):
|
| 119 |
+
return x.tolist()
|
| 120 |
+
if isinstance(x, (pd.Series,)):
|
| 121 |
+
return x.astype(object).where(~x.isna(), None).tolist()
|
| 122 |
+
if isinstance(x, (pd.DataFrame,)):
|
| 123 |
+
return x.to_dict(orient="list")
|
| 124 |
+
return x
|
| 125 |
+
|
| 126 |
+
def _json_safe(obj):
|
| 127 |
+
# recursively convert to JSON-serializable Python types
|
| 128 |
+
if isinstance(obj, dict):
|
| 129 |
+
return {str(k): _json_safe(v) for k, v in obj.items()}
|
| 130 |
+
if isinstance(obj, (list, tuple, set)):
|
| 131 |
+
return [_json_safe(v) for v in obj]
|
| 132 |
+
return _to_py_scalar(obj)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _balance_training_raw(
|
| 136 |
+
X_train_raw: pd.DataFrame,
|
| 137 |
+
y_train: pd.Series,
|
| 138 |
+
balancing_mode: str, # 'none' | 'over' | 'smote' | 'gans'
|
| 139 |
+
augmentation_mode: str, # 'none' | 'gans'
|
| 140 |
+
categorical_cols: List[str],
|
| 141 |
+
target_samples: Optional[int],
|
| 142 |
+
random_state: int,
|
| 143 |
+
progress_fn: Optional[Callable[[float, str], None]] = None,
|
| 144 |
+
) -> Tuple[pd.DataFrame, pd.Series]:
|
| 145 |
+
"""
|
| 146 |
+
Modify ONLY THE TRAINING SPLIT, in RAW space (pre-scaling, pre-encoding).
|
| 147 |
+
|
| 148 |
+
Steps:
|
| 149 |
+
1. balance (if requested)
|
| 150 |
+
2. then augment (if requested)
|
| 151 |
+
|
| 152 |
+
Returns new (X_train_raw_balanced_augmented, y_train_balanced_augmented).
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
Xb = X_train_raw.reset_index(drop=True).copy()
|
| 156 |
+
yb = y_train.reset_index(drop=True).astype(int)
|
| 157 |
+
|
| 158 |
+
# let the UI know we entered balancing
|
| 159 |
+
if progress_fn:
|
| 160 |
+
progress_fn(15, "Balancing training split...")
|
| 161 |
+
|
| 162 |
+
# --- 1. BALANCING -------------------------------------------------
|
| 163 |
+
if balancing_mode == 'none':
|
| 164 |
+
if progress_fn:
|
| 165 |
+
progress_fn(16, "No class balancing requested.")
|
| 166 |
+
|
| 167 |
+
elif balancing_mode == 'over':
|
| 168 |
+
if progress_fn:
|
| 169 |
+
progress_fn(16, "Applying random oversampling...")
|
| 170 |
+
# bootstrap minority class to match majority
|
| 171 |
+
train_df = Xb.copy()
|
| 172 |
+
train_df['__y__'] = yb.values
|
| 173 |
+
counts = train_df['__y__'].value_counts()
|
| 174 |
+
if len(counts) >= 2:
|
| 175 |
+
maj_class = counts.idxmax()
|
| 176 |
+
maj_df = train_df[train_df['__y__'] == maj_class]
|
| 177 |
+
min_df = train_df[train_df['__y__'] != maj_class]
|
| 178 |
+
|
| 179 |
+
if len(min_df) > 0 and len(maj_df) > 0:
|
| 180 |
+
from sklearn.utils import resample
|
| 181 |
+
min_up = resample(
|
| 182 |
+
min_df,
|
| 183 |
+
replace=True,
|
| 184 |
+
n_samples=len(maj_df),
|
| 185 |
+
random_state=random_state,
|
| 186 |
+
)
|
| 187 |
+
up_df = pd.concat([maj_df, min_up]).sample(
|
| 188 |
+
frac=1, random_state=random_state
|
| 189 |
+
)
|
| 190 |
+
yb = up_df['__y__'].astype(int).reset_index(drop=True)
|
| 191 |
+
Xb = up_df.drop(columns=['__y__']).reset_index(drop=True)
|
| 192 |
+
|
| 193 |
+
elif balancing_mode == 'smote':
|
| 194 |
+
if progress_fn:
|
| 195 |
+
progress_fn(16, "Running SMOTE...")
|
| 196 |
+
# figure out categorical col indices
|
| 197 |
+
cat_idx = [Xb.columns.get_loc(c) for c in categorical_cols if c in Xb.columns]
|
| 198 |
+
|
| 199 |
+
if len(cat_idx) == 0:
|
| 200 |
+
# all features are numeric -> use regular SMOTE
|
| 201 |
+
from imblearn.over_sampling import SMOTE
|
| 202 |
+
sm = SMOTE(random_state=random_state)
|
| 203 |
+
else:
|
| 204 |
+
from imblearn.over_sampling import SMOTENC
|
| 205 |
+
sm = SMOTENC(
|
| 206 |
+
categorical_features=cat_idx,
|
| 207 |
+
random_state=random_state,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
X_res, y_res = sm.fit_resample(Xb, yb)
|
| 211 |
+
|
| 212 |
+
Xb = pd.DataFrame(X_res, columns=Xb.columns).reset_index(drop=True)
|
| 213 |
+
yb = pd.Series(y_res, name=yb.name).astype(int).reset_index(drop=True)
|
| 214 |
+
|
| 215 |
+
elif balancing_mode == 'gans':
|
| 216 |
+
if progress_fn:
|
| 217 |
+
progress_fn(16, "Training CTGAN to balance minority class...")
|
| 218 |
+
# CTGAN upsample minority class to match majority
|
| 219 |
+
Xb, yb = _apply_ctgan_on_raw(
|
| 220 |
+
X_train_raw=Xb,
|
| 221 |
+
y_train=yb,
|
| 222 |
+
categorical_cols=categorical_cols,
|
| 223 |
+
do_balance=True, # <-- balance minority up to majority
|
| 224 |
+
do_augment=False, # <-- NOT doing bulk growth yet
|
| 225 |
+
target_samples=None,
|
| 226 |
+
random_state=random_state,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
else:
|
| 230 |
+
raise ValueError(f"Unknown balancing mode: {balancing_mode}")
|
| 231 |
+
|
| 232 |
+
if progress_fn:
|
| 233 |
+
progress_fn(17, "Balancing complete.")
|
| 234 |
+
|
| 235 |
+
# --- 2. AUGMENTATION ----------------------------------------------
|
| 236 |
+
# still ONLY training data, just making more rows if requested
|
| 237 |
+
if augmentation_mode == 'gans':
|
| 238 |
+
if progress_fn:
|
| 239 |
+
progress_fn(18, "Generating extra synthetic samples (augmentation)...")
|
| 240 |
+
|
| 241 |
+
Xb, yb = _apply_ctgan_on_raw(
|
| 242 |
+
X_train_raw=Xb,
|
| 243 |
+
y_train=yb,
|
| 244 |
+
categorical_cols=categorical_cols,
|
| 245 |
+
do_balance=False, # don't rebalance again
|
| 246 |
+
do_augment=True, # add extra synthetic samples
|
| 247 |
+
target_samples=target_samples,
|
| 248 |
+
random_state=random_state,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
if progress_fn:
|
| 252 |
+
progress_fn(18, "Augmentation complete.")
|
| 253 |
+
|
| 254 |
+
elif augmentation_mode == 'none':
|
| 255 |
+
if progress_fn:
|
| 256 |
+
progress_fn(19.0, "No augmentation requested.")
|
| 257 |
+
pass
|
| 258 |
+
else:
|
| 259 |
+
raise ValueError(f"Unknown augmentation mode: {augmentation_mode}")
|
| 260 |
+
|
| 261 |
+
return (
|
| 262 |
+
Xb.reset_index(drop=True),
|
| 263 |
+
yb.reset_index(drop=True).astype(int),
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _create_mlp(input_dim: int, dropout_rate: float = 0.2, learning_rate: float = 0.001):
|
| 268 |
+
model = Sequential()
|
| 269 |
+
model.add(Input(shape=(input_dim,)))
|
| 270 |
+
model.add(Dense(128, activation='relu'))
|
| 271 |
+
model.add(Dropout(dropout_rate))
|
| 272 |
+
model.add(Dense(64, activation='relu'))
|
| 273 |
+
model.add(Dropout(dropout_rate))
|
| 274 |
+
model.add(Dense(1, activation='sigmoid'))
|
| 275 |
+
model.compile(
|
| 276 |
+
optimizer=Adam(learning_rate=learning_rate),
|
| 277 |
+
loss='binary_crossentropy',
|
| 278 |
+
metrics=[tf.keras.metrics.AUC(name='auc')]
|
| 279 |
+
)
|
| 280 |
+
return model
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _pretty_feature_names(names: List[str]) -> List[str]:
|
| 285 |
+
out = []
|
| 286 |
+
for n in names:
|
| 287 |
+
s = str(n)
|
| 288 |
+
# drop ColumnTransformer prefixes like "num__", "num_", "cat__", "cat_"
|
| 289 |
+
s = re.sub(r'^(num|cat)_{1,2}', '', s)
|
| 290 |
+
# keep it tidy
|
| 291 |
+
out.append(s if len(s) <= 40 else s[:37] + '…')
|
| 292 |
+
return out
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _stratify_or_none(y: pd.Series):
|
| 297 |
+
vc = y.value_counts(dropna=False)
|
| 298 |
+
return y if (len(vc) >= 2 and vc.min() >= 2) else None
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _get_base_model(key: str, input_dim: Optional[int] = None):
|
| 302 |
+
if key == 'rf':
|
| 303 |
+
return RandomForestClassifier()
|
| 304 |
+
if key == 'svm':
|
| 305 |
+
return SVC(probability=True)
|
| 306 |
+
if key == 'knn':
|
| 307 |
+
return KNeighborsClassifier()
|
| 308 |
+
if key == 'lr':
|
| 309 |
+
return LogisticRegression(max_iter=10_000)
|
| 310 |
+
if key == 'gb':
|
| 311 |
+
return GradientBoostingClassifier()
|
| 312 |
+
if key == 'xgb' and _XGB_OK:
|
| 313 |
+
return XGBClassifier(eval_metric='logloss')
|
| 314 |
+
if key == 'mlp' and _MLP_OK and input_dim is not None:
|
| 315 |
+
return KerasClassifier(model=_create_mlp, model__input_dim=input_dim, verbose=0)
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _ctgan_sample_raw(df_raw: pd.DataFrame, discrete_cols: List[str], n: int, epochs: int = 300, seed: int = 42) -> pd.DataFrame:
|
| 320 |
+
if n <= 0:
|
| 321 |
+
return pd.DataFrame(columns=df_raw.columns)
|
| 322 |
+
if not _CTGAN_OK:
|
| 323 |
+
raise RuntimeError("CTGAN requested but the 'ctgan' package is not installed.")
|
| 324 |
+
|
| 325 |
+
synth = _CTGANClass(epochs=epochs, verbose=False)
|
| 326 |
+
synth.fit(df_raw, discrete_columns=discrete_cols)
|
| 327 |
+
out = synth.sample(n)
|
| 328 |
+
return out.reset_index(drop=True)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _apply_ctgan_on_raw(
|
| 332 |
+
X_train_raw: pd.DataFrame,
|
| 333 |
+
y_train: pd.Series,
|
| 334 |
+
categorical_cols: List[str],
|
| 335 |
+
do_balance: bool,
|
| 336 |
+
do_augment: bool,
|
| 337 |
+
target_samples: Optional[int],
|
| 338 |
+
random_state: int,
|
| 339 |
+
) -> Tuple[pd.DataFrame, pd.Series]:
|
| 340 |
+
"""
|
| 341 |
+
Mirror the script: balance minority to majority on RAW columns (with categoricals),
|
| 342 |
+
then optionally augment to target_samples. Returns new (X_raw, y).
|
| 343 |
+
"""
|
| 344 |
+
train_df = X_train_raw.copy()
|
| 345 |
+
train_df['__y__'] = y_train.values.astype(int)
|
| 346 |
+
|
| 347 |
+
# Balance
|
| 348 |
+
if do_balance:
|
| 349 |
+
vc = train_df['__y__'].value_counts()
|
| 350 |
+
if len(vc) >= 2:
|
| 351 |
+
minority = int(vc.idxmin())
|
| 352 |
+
majority_n = int(vc.max())
|
| 353 |
+
need = majority_n - int((train_df['__y__'] == minority).sum())
|
| 354 |
+
if need > 0:
|
| 355 |
+
minority_df = train_df[train_df['__y__'] == minority].reset_index(drop=True)
|
| 356 |
+
synth = _ctgan_sample_raw(
|
| 357 |
+
minority_df,
|
| 358 |
+
discrete_cols=categorical_cols + ['__y__'],
|
| 359 |
+
n=need,
|
| 360 |
+
epochs=300,
|
| 361 |
+
seed=random_state,
|
| 362 |
+
)
|
| 363 |
+
train_df = pd.concat([train_df, synth], ignore_index=True)
|
| 364 |
+
|
| 365 |
+
# Augment
|
| 366 |
+
if do_augment and target_samples is not None and target_samples > len(train_df):
|
| 367 |
+
need_total = int(target_samples - len(train_df))
|
| 368 |
+
vc = train_df['__y__'].value_counts()
|
| 369 |
+
ratio = vc / vc.sum()
|
| 370 |
+
alloc = {int(cls): int(round(need_total * p)) for cls, p in ratio.items()}
|
| 371 |
+
diff = need_total - sum(alloc.values())
|
| 372 |
+
if diff:
|
| 373 |
+
alloc[int(vc.idxmax())] = alloc.get(int(vc.idxmax()), 0) + diff
|
| 374 |
+
|
| 375 |
+
# Fit once on the current (balanced) RAW table and sample in batches
|
| 376 |
+
# (simple approach: sample, then filter by class)
|
| 377 |
+
parts = [train_df]
|
| 378 |
+
for cls, n_add in alloc.items():
|
| 379 |
+
if n_add <= 0:
|
| 380 |
+
continue
|
| 381 |
+
got = pd.DataFrame()
|
| 382 |
+
tries = 0
|
| 383 |
+
while len(got) < n_add and tries < 5:
|
| 384 |
+
batch = _ctgan_sample_raw(
|
| 385 |
+
train_df, discrete_cols=categorical_cols + ['__y__'],
|
| 386 |
+
n=max(n_add * 2, 200), epochs=300, seed=random_state + tries
|
| 387 |
+
)
|
| 388 |
+
batch = batch[batch['__y__'] == cls]
|
| 389 |
+
got = pd.concat([got, batch], ignore_index=True).head(n_add)
|
| 390 |
+
tries += 1
|
| 391 |
+
if len(got) < n_add:
|
| 392 |
+
# fallback: unconditional sample (keep whatever class proportion arrives)
|
| 393 |
+
got = _ctgan_sample_raw(
|
| 394 |
+
train_df, discrete_cols=categorical_cols + ['__y__'],
|
| 395 |
+
n=n_add, epochs=300, seed=random_state + 99
|
| 396 |
+
)
|
| 397 |
+
# best-effort: trim/keep to n_add
|
| 398 |
+
got = got.head(n_add)
|
| 399 |
+
parts.append(got)
|
| 400 |
+
train_df = pd.concat(parts, ignore_index=True)
|
| 401 |
+
|
| 402 |
+
y_out = train_df['__y__'].astype(int).reset_index(drop=True)
|
| 403 |
+
X_out = train_df.drop(columns=['__y__']).reset_index(drop=True)
|
| 404 |
+
return X_out, y_out
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _param_grid(key: str, input_dim: Optional[int] = None) -> Dict[str, List[Any]]:
|
| 408 |
+
grids = {
|
| 409 |
+
'rf': { 'n_estimators': [100, 200, 300], 'max_depth': [None, 10, 20, 30],'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4],'bootstrap': [True, False] },
|
| 410 |
+
'svm': {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf', 'poly'], 'gamma': ['scale', 'auto'], 'degree': [3, 4, 5]},
|
| 411 |
+
'knn': {'n_neighbors': [3, 5, 7, 11], 'weights': ['uniform', 'distance'], 'metric': ['euclidean', 'manhattan'] },
|
| 412 |
+
'lr': {'C': [0.01, 0.1, 1, 10, 100],'penalty': ['l1', 'l2'],'solver': ['liblinear', 'saga'],'max_iter': [100, 500, 1000]},
|
| 413 |
+
'gb': {'n_estimators': [100, 200],'learning_rate': [0.01, 0.1, 0.2],'max_depth': [3, 5, 7],'subsample': [0.8, 1.0],'min_samples_split': [2, 5],'min_samples_leaf': [1, 2]},
|
| 414 |
+
'xgb': {'n_estimators': [100, 200],'learning_rate': [0.01, 0.1, 0.2],'max_depth': [3, 5, 7],'subsample': [0.8, 1.0],'colsample_bytree': [0.6, 0.8, 1.0],'gamma': [0, 0.1, 0.2]},
|
| 415 |
+
'mlp': {'model__hidden_layers': [[64],[128, 64],[128, 64, 32]],'model__dropout_rate': [0.2, 0.3],'model__learning_rate': [0.001, 0.0005],'epochs': [30, 50],'batch_size': [16, 32]}
|
| 416 |
+
}
|
| 417 |
+
if key == 'mlp' and _MLP_OK and input_dim is not None:
|
| 418 |
+
return {
|
| 419 |
+
'model__input_dim': [input_dim],
|
| 420 |
+
'model__dropout_rate': [0.2, 0.3],
|
| 421 |
+
'model__learning_rate': [0.001, 0.0005],
|
| 422 |
+
'epochs': [25, 40],
|
| 423 |
+
'batch_size': [16, 32],
|
| 424 |
+
}
|
| 425 |
+
return grids.get(key, {})
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def _get_meta_learner(key: str):
|
| 429 |
+
if key == 'lr':
|
| 430 |
+
return LogisticRegression(max_iter=10_000)
|
| 431 |
+
if key == 'rf':
|
| 432 |
+
return RandomForestClassifier()
|
| 433 |
+
if key == 'gb':
|
| 434 |
+
return GradientBoostingClassifier()
|
| 435 |
+
return LogisticRegression(max_iter=10_000)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _score_auc_f1(estimator, X: pd.DataFrame, y: pd.Series) -> Tuple[Optional[float], float]:
|
| 439 |
+
"""Uniform scoring helper that returns plain-Python floats (JSON-safe)."""
|
| 440 |
+
y_pred = estimator.predict(X)
|
| 441 |
+
f1 = float(f1_score(y, y_pred))
|
| 442 |
+
auc = None
|
| 443 |
+
if hasattr(estimator, "predict_proba"):
|
| 444 |
+
try:
|
| 445 |
+
auc = float(roc_auc_score(y, estimator.predict_proba(X)[:, 1]))
|
| 446 |
+
except ValueError:
|
| 447 |
+
auc = None
|
| 448 |
+
return auc, f1
|
| 449 |
+
|
| 450 |
+
# ------------------------------------------------------------------------------
|
| 451 |
+
# Explainability plots
|
| 452 |
+
# ------------------------------------------------------------------------------
|
| 453 |
+
def _make_shap_plot_if_possible(
|
| 454 |
+
model, X_bg: pd.DataFrame, X_eval: pd.DataFrame, feature_names: List[str], run_id: str
|
| 455 |
+
) -> Optional[str]:
|
| 456 |
+
"""Return MEDIA-relative path to SHAP bar summary, or None on failure."""
|
| 457 |
+
if not _SHAP_OK:
|
| 458 |
+
return None
|
| 459 |
+
|
| 460 |
+
bg = X_bg.sample(min(50, len(X_bg)), random_state=0).reset_index(drop=True)
|
| 461 |
+
ev = X_eval.sample(min(200, len(X_eval)), random_state=1).reset_index(drop=True)
|
| 462 |
+
|
| 463 |
+
try:
|
| 464 |
+
explainer = shap.Explainer(model, bg)
|
| 465 |
+
sv = explainer(ev)
|
| 466 |
+
shap.summary_plot(sv, features=ev, feature_names=feature_names, plot_type="bar", show=False)
|
| 467 |
+
except Exception:
|
| 468 |
+
try:
|
| 469 |
+
def _f(X):
|
| 470 |
+
Xdf = pd.DataFrame(X, columns=feature_names)
|
| 471 |
+
if hasattr(model, "predict_proba"):
|
| 472 |
+
return model.predict_proba(Xdf)[:, 1]
|
| 473 |
+
return model.predict(Xdf)
|
| 474 |
+
|
| 475 |
+
kexp = shap.KernelExplainer(_f, bg)
|
| 476 |
+
sv = kexp.shap_values(ev, nsamples=100)
|
| 477 |
+
shap.summary_plot(sv, ev, feature_names=feature_names, plot_type="bar", show=False)
|
| 478 |
+
except Exception:
|
| 479 |
+
try:
|
| 480 |
+
plt.close()
|
| 481 |
+
except Exception:
|
| 482 |
+
pass
|
| 483 |
+
return None
|
| 484 |
+
|
| 485 |
+
plt.tight_layout()
|
| 486 |
+
rel_dir = os.path.join("train_runs")
|
| 487 |
+
abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir)
|
| 488 |
+
os.makedirs(abs_dir, exist_ok=True)
|
| 489 |
+
rel_path = os.path.join(rel_dir, f"{run_id}_shap.svg") # needs to be SVG to then be responsive
|
| 490 |
+
plt.gcf().set_size_inches(8, 5)
|
| 491 |
+
plt.savefig(os.path.join(abs_dir, f"{run_id}_shap.svg"),format="svg", bbox_inches="tight") # ← SVG export
|
| 492 |
+
plt.close()
|
| 493 |
+
return rel_path
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def _make_perm_plot_if_possible(
|
| 497 |
+
model, X_eval: pd.DataFrame, y_eval: pd.Series, feature_names: List[str], run_id: str
|
| 498 |
+
) -> Optional[str]:
|
| 499 |
+
"""Return MEDIA-relative path to permutation-importance plot, or None on failure."""
|
| 500 |
+
try:
|
| 501 |
+
res = permutation_importance(model, X_eval, y_eval, n_repeats=10, random_state=0, scoring="roc_auc")
|
| 502 |
+
names = feature_names if feature_names and len(feature_names) == X_eval.shape[1] else list(X_eval.columns)
|
| 503 |
+
names = _pretty_feature_names(names)
|
| 504 |
+
imps = pd.Series(res.importances_mean, index=names).fillna(0.0)
|
| 505 |
+
|
| 506 |
+
top = imps.sort_values().tail(25)
|
| 507 |
+
plt.figure(figsize=(12, 6), dpi=140)
|
| 508 |
+
colors = ['tab:red' if v < 0 else 'tab:green' for v in top.values]
|
| 509 |
+
plt.barh(top.index, top.values, color=colors, alpha=0.9)
|
| 510 |
+
plt.axvline(0, linestyle='--', linewidth=1, alpha=0.6)
|
| 511 |
+
plt.title("Permutation importance (validation)")
|
| 512 |
+
plt.xlabel("Mean change in ROC AUC when permuted")
|
| 513 |
+
plt.tight_layout()
|
| 514 |
+
|
| 515 |
+
rel_dir = os.path.join("train_runs")
|
| 516 |
+
abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir)
|
| 517 |
+
os.makedirs(abs_dir, exist_ok=True)
|
| 518 |
+
rel_path = os.path.join(rel_dir, f"{run_id}_perm.svg")
|
| 519 |
+
plt.savefig(os.path.join(abs_dir, f"{run_id}_perm.svg"), format="svg", bbox_inches="tight")
|
| 520 |
+
plt.close()
|
| 521 |
+
return rel_path
|
| 522 |
+
except Exception:
|
| 523 |
+
try:
|
| 524 |
+
plt.close()
|
| 525 |
+
except Exception:
|
| 526 |
+
pass
|
| 527 |
+
return None
|
| 528 |
+
|
| 529 |
+
# ------------------------------------------------------------------------------
|
| 530 |
+
# Feature selection helpers
|
| 531 |
+
# ------------------------------------------------------------------------------
|
| 532 |
+
def _rfecv_k_per_base(X_train_proc: pd.DataFrame, y_train: pd.Series) -> Tuple[Dict[str, int], Dict[str, RFECV]]:
|
| 533 |
+
"""Run RFECV with a few base estimators to infer a sensible k (cap at 20)."""
|
| 534 |
+
bases = {
|
| 535 |
+
'lr': LogisticRegression(max_iter=10_000),
|
| 536 |
+
'rf': RandomForestClassifier(),
|
| 537 |
+
'svm': SVC(kernel='linear', probability=True),
|
| 538 |
+
}
|
| 539 |
+
k_map, model_map = {}, {}
|
| 540 |
+
for name, est in bases.items():
|
| 541 |
+
rfecv = RFECV(estimator=est, step=1, cv=3, scoring='roc_auc', n_jobs=-1)
|
| 542 |
+
rfecv.fit(X_train_proc, y_train)
|
| 543 |
+
k = min(20, getattr(rfecv, "n_features_", X_train_proc.shape[1]))
|
| 544 |
+
k_map[name] = k
|
| 545 |
+
model_map[name] = rfecv
|
| 546 |
+
return k_map, model_map
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _select_features(
|
| 550 |
+
method: str,
|
| 551 |
+
X_train_proc: pd.DataFrame,
|
| 552 |
+
y_train: pd.Series,
|
| 553 |
+
X_val_proc: pd.DataFrame,
|
| 554 |
+
k: int,
|
| 555 |
+
rfecv_model: Optional[RFECV] = None
|
| 556 |
+
) -> Tuple[pd.DataFrame, pd.DataFrame, Optional[SelectKBest], List[str]]:
|
| 557 |
+
"""
|
| 558 |
+
Returns train/val reduced, optional selector object (only for kbest), and feature names.
|
| 559 |
+
"""
|
| 560 |
+
selector_obj = None
|
| 561 |
+
if method == 'rfe':
|
| 562 |
+
ranking = rfecv_model.ranking_
|
| 563 |
+
ranks = pd.Series(ranking, index=X_train_proc.columns).sort_values()
|
| 564 |
+
feats = list(ranks.index[:k])
|
| 565 |
+
return X_train_proc[feats], X_val_proc[feats], selector_obj, feats
|
| 566 |
+
|
| 567 |
+
selector_obj = SelectKBest(score_func=mutual_info_classif, k=k)
|
| 568 |
+
selector_obj.fit(X_train_proc, y_train)
|
| 569 |
+
scores = pd.Series(selector_obj.scores_, index=X_train_proc.columns).sort_values(ascending=False)
|
| 570 |
+
feats = list(scores.index[:k])
|
| 571 |
+
return X_train_proc[feats], X_val_proc[feats], selector_obj, feats
|
| 572 |
+
|
| 573 |
+
# ------------------------------------------------------------------------------
|
| 574 |
+
# Public entry point
|
| 575 |
+
# ------------------------------------------------------------------------------
|
| 576 |
+
def train_dataset(
|
| 577 |
+
file_obj,
|
| 578 |
+
opts: TrainOptions,
|
| 579 |
+
save_to: Optional[str] = None,
|
| 580 |
+
progress_cb: Optional[Callable[[float, str], None]] = None, # <— NEW
|
| 581 |
+
) -> TrainResult:
|
| 582 |
+
def _emit(pct: float, msg: str):
|
| 583 |
+
if progress_cb:
|
| 584 |
+
try:
|
| 585 |
+
progress_cb(float(pct), str(msg))
|
| 586 |
+
except Exception:
|
| 587 |
+
pass
|
| 588 |
+
|
| 589 |
+
# --- sanitize target_samples (form can send '') ---
|
| 590 |
+
if isinstance(opts.target_samples, str):
|
| 591 |
+
target_samples = int(opts.target_samples) if opts.target_samples.strip() else None
|
| 592 |
+
else:
|
| 593 |
+
target_samples = opts.target_samples
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
# ---- Load & sanitize
|
| 597 |
+
_emit(1, "Reading CSV...")
|
| 598 |
+
df = pd.read_csv(file_obj)
|
| 599 |
+
if 'healthy' not in df.columns:
|
| 600 |
+
raise ValueError("CSV must include a 'healthy' column (0/1).")
|
| 601 |
+
|
| 602 |
+
drop_cols = [c for c in ['sample_id', 'id'] if c in df.columns]
|
| 603 |
+
if drop_cols:
|
| 604 |
+
df = df.drop(columns=drop_cols)
|
| 605 |
+
|
| 606 |
+
# coerce object columns that look numeric
|
| 607 |
+
for c in df.columns:
|
| 608 |
+
if df[c].dtype == object:
|
| 609 |
+
coerced = pd.to_numeric(df[c], errors='coerce')
|
| 610 |
+
if coerced.notna().sum() > 0:
|
| 611 |
+
df[c] = coerced
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
df = df.dropna(axis=0, how='any').reset_index(drop=True)
|
| 615 |
+
|
| 616 |
+
raw_feature_cols = [c for c in df.columns if c != 'healthy']
|
| 617 |
+
X = df[raw_feature_cols].copy()
|
| 618 |
+
y = df['healthy'].astype(int)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
# ---- Split (fit preprocessors on TRAIN only)
|
| 622 |
+
_emit(8, "Splitting train/val/test...")
|
| 623 |
+
X_dev, X_test, y_dev, y_test = train_test_split(
|
| 624 |
+
X, y, test_size=opts.test_size, stratify=_stratify_or_none(y), random_state=opts.random_state
|
| 625 |
+
)
|
| 626 |
+
X_train_raw, X_val_raw, y_train, y_val = train_test_split(
|
| 627 |
+
X_dev, y_dev, test_size=opts.val_size, stratify=_stratify_or_none(y_dev), random_state=opts.random_state
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
# ---- Identify numeric vs categorical on TRAIN RAW (before balancing) ----
|
| 631 |
+
numeric_cols = X_train_raw.select_dtypes(include=[np.number, bool]).columns.tolist()
|
| 632 |
+
categorical_cols = X_train_raw.columns.difference(numeric_cols).tolist()
|
| 633 |
+
|
| 634 |
+
_emit(15, "Balancing / augmentation on training split...")
|
| 635 |
+
|
| 636 |
+
X_train_raw, y_train = _balance_training_raw(
|
| 637 |
+
X_train_raw=X_train_raw,
|
| 638 |
+
y_train=y_train,
|
| 639 |
+
balancing_mode=opts.balancing,
|
| 640 |
+
augmentation_mode=opts.augmentation,
|
| 641 |
+
categorical_cols=categorical_cols,
|
| 642 |
+
target_samples=target_samples,
|
| 643 |
+
random_state=opts.random_state,
|
| 644 |
+
progress_fn=_emit,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
num_pipe = Pipeline(steps=[
|
| 648 |
+
('scale', StandardScaler() if opts.scaler == 'standard' else MinMaxScaler()),
|
| 649 |
+
])
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
try:
|
| 653 |
+
ohe = OneHotEncoder(handle_unknown='ignore', sparse_output=False)
|
| 654 |
+
except TypeError:
|
| 655 |
+
ohe = OneHotEncoder(handle_unknown='ignore', sparse=False)
|
| 656 |
+
|
| 657 |
+
cat_pipe = Pipeline(steps=[
|
| 658 |
+
('ohe', ohe),
|
| 659 |
+
])
|
| 660 |
+
|
| 661 |
+
preprocessor = ColumnTransformer(
|
| 662 |
+
transformers=[
|
| 663 |
+
('num', num_pipe, numeric_cols),
|
| 664 |
+
('cat', cat_pipe, categorical_cols),
|
| 665 |
+
],
|
| 666 |
+
remainder='drop'
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
_emit(25, "Fitting preprocessors...")
|
| 670 |
+
preprocessor.fit(X_train_raw)
|
| 671 |
+
|
| 672 |
+
def _to_df(arr):
|
| 673 |
+
names = preprocessor.get_feature_names_out().tolist()
|
| 674 |
+
return pd.DataFrame(arr, columns=names).astype(np.float32)
|
| 675 |
+
|
| 676 |
+
X_train_proc = _to_df(preprocessor.transform(X_train_raw))
|
| 677 |
+
X_val_proc = _to_df(preprocessor.transform(X_val_raw))
|
| 678 |
+
X_test_proc = _to_df(preprocessor.transform(X_test))
|
| 679 |
+
|
| 680 |
+
# Ensure labels align with 0..n-1 indices produced by transform()
|
| 681 |
+
y_train = y_train.reset_index(drop=True)
|
| 682 |
+
y_val = y_val.reset_index(drop=True)
|
| 683 |
+
y_test = y_test.reset_index(drop=True)
|
| 684 |
+
|
| 685 |
+
# keep tidy indices after any resampling
|
| 686 |
+
X_train_proc = X_train_proc.reset_index(drop=True)
|
| 687 |
+
y_train = y_train.reset_index(drop=True).astype(int)
|
| 688 |
+
|
| 689 |
+
# ---- Feature selection candidates
|
| 690 |
+
_emit(35, "Running RFECV...")
|
| 691 |
+
k_map, rfecv_map = _rfecv_k_per_base(X_train_proc, y_train) # k cap at 20 per base
|
| 692 |
+
selection_methods = ['rfe', 'kbest']
|
| 693 |
+
done_slices = 0
|
| 694 |
+
total_slices = max(1, len(selection_methods) * len(k_map))
|
| 695 |
+
|
| 696 |
+
# if multiple base models but 'none' ensemble, nudge to stacking
|
| 697 |
+
ensemble_type = 'stacking' if (len(opts.base_models) >= 2 and opts.ensemble_type == 'none') else opts.ensemble_type
|
| 698 |
+
|
| 699 |
+
best_val_key = None
|
| 700 |
+
best_val_metrics = (-1.0, -1.0) # (auc, f1)
|
| 701 |
+
best_pack: Dict[str, Any] = {}
|
| 702 |
+
|
| 703 |
+
for method in selection_methods:
|
| 704 |
+
for k_base_name, k in k_map.items():
|
| 705 |
+
done_slices += 1
|
| 706 |
+
_emit(35 + 45 * (done_slices - 1) / total_slices, f"Training {method} / {k_base_name} (k={k})...")
|
| 707 |
+
Xtr_sel, Xv_sel, selector_obj, feats = _select_features(
|
| 708 |
+
method, X_train_proc, y_train, X_val_proc, k, rfecv_map.get(k_base_name)
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Instantiate requested base models
|
| 712 |
+
chosen_models = []
|
| 713 |
+
for key in opts.base_models:
|
| 714 |
+
mdl = _get_base_model(key, input_dim=Xtr_sel.shape[1])
|
| 715 |
+
if mdl is not None:
|
| 716 |
+
chosen_models.append((key, mdl))
|
| 717 |
+
|
| 718 |
+
# Hyperparam tune or fit directly
|
| 719 |
+
best_estimators: Dict[str, Any] = {}
|
| 720 |
+
for key, mdl in chosen_models:
|
| 721 |
+
grid_params = copy.deepcopy(_param_grid(key, input_dim=Xtr_sel.shape[1]))
|
| 722 |
+
if grid_params:
|
| 723 |
+
gs = GridSearchCV(mdl, grid_params, cv=3, scoring='roc_auc', n_jobs=-1)
|
| 724 |
+
gs.fit(Xtr_sel, y_train)
|
| 725 |
+
best_est = gs.best_estimator_
|
| 726 |
+
else:
|
| 727 |
+
mdl.fit(Xtr_sel, y_train)
|
| 728 |
+
best_est = mdl
|
| 729 |
+
best_estimators[key] = best_est
|
| 730 |
+
|
| 731 |
+
if len(best_estimators) == 0:
|
| 732 |
+
continue
|
| 733 |
+
|
| 734 |
+
# Build final model for this feature slice
|
| 735 |
+
if len(best_estimators) == 1 or ensemble_type == 'none':
|
| 736 |
+
# choose best single model by (AUC, F1) on VAL
|
| 737 |
+
auc_f1_list = []
|
| 738 |
+
for key, est in best_estimators.items():
|
| 739 |
+
auc, f1 = _score_auc_f1(est, Xv_sel, y_val)
|
| 740 |
+
auc_f1_list.append((auc if auc is not None else -1, f1, key, est))
|
| 741 |
+
auc_f1_list.sort(reverse=True)
|
| 742 |
+
_, _, label, final_model = auc_f1_list[0]
|
| 743 |
+
|
| 744 |
+
elif ensemble_type == 'voting':
|
| 745 |
+
voting = opts.voting_type or 'hard'
|
| 746 |
+
final_model = VotingClassifier(estimators=list(best_estimators.items()), voting=voting)
|
| 747 |
+
final_model.fit(Xtr_sel, y_train)
|
| 748 |
+
label = f"Voting({voting})"
|
| 749 |
+
|
| 750 |
+
else: # 'stacking'
|
| 751 |
+
meta = _get_meta_learner(opts.meta_learner or 'lr')
|
| 752 |
+
final_model = StackingClassifier(
|
| 753 |
+
estimators=list(best_estimators.items()),
|
| 754 |
+
final_estimator=clone(meta),
|
| 755 |
+
passthrough=True, cv=3, n_jobs=-1
|
| 756 |
+
)
|
| 757 |
+
final_model.fit(Xtr_sel, y_train)
|
| 758 |
+
label = f"Stacking({opts.meta_learner or 'lr'})"
|
| 759 |
+
|
| 760 |
+
# Validate
|
| 761 |
+
val_auc, val_f1 = _score_auc_f1(final_model, Xv_sel, y_val)
|
| 762 |
+
key_tuple = (val_auc if val_auc is not None else -1, val_f1)
|
| 763 |
+
|
| 764 |
+
if key_tuple > best_val_metrics:
|
| 765 |
+
best_val_metrics = key_tuple
|
| 766 |
+
best_val_key = (method, k_base_name, k, label)
|
| 767 |
+
best_pack = {
|
| 768 |
+
"model": final_model,
|
| 769 |
+
"selector": selector_obj if method == 'kbest' else None,
|
| 770 |
+
"final_features": feats,
|
| 771 |
+
"pre_features": list(X_train_proc.columns),
|
| 772 |
+
"preprocessor": preprocessor,
|
| 773 |
+
"scaler_type": opts.scaler,
|
| 774 |
+
"feature_method": method,
|
| 775 |
+
"k_from": k_base_name,
|
| 776 |
+
"k": k,
|
| 777 |
+
"ensemble": ensemble_type,
|
| 778 |
+
"base_models": list(best_estimators.keys()),
|
| 779 |
+
"meta_learner": (opts.meta_learner if ensemble_type == "stacking" else None),
|
| 780 |
+
"voting_type": (opts.voting_type if ensemble_type == "voting" else None),
|
| 781 |
+
"balancing": opts.balancing,
|
| 782 |
+
"augmentation": opts.augmentation,
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
if not best_pack:
|
| 786 |
+
raise RuntimeError("No valid model configuration could be trained.")
|
| 787 |
+
|
| 788 |
+
# ---- Test once on held-out
|
| 789 |
+
if best_pack["selector"] is not None:
|
| 790 |
+
X_test_aligned = X_test_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0)
|
| 791 |
+
Xte_sel_arr = best_pack["selector"].transform(X_test_aligned)
|
| 792 |
+
Xte_sel = pd.DataFrame(Xte_sel_arr, columns=best_pack["final_features"])
|
| 793 |
+
else:
|
| 794 |
+
Xte_sel = X_test_proc[best_pack["final_features"]]
|
| 795 |
+
|
| 796 |
+
_emit(85, "Testing on hold-out...")
|
| 797 |
+
test_auc, test_f1 = _score_auc_f1(best_pack["model"], Xte_sel, y_test)
|
| 798 |
+
val_auc, val_f1 = best_val_metrics
|
| 799 |
+
|
| 800 |
+
# Plain-Python scalars for anything we might serialize/store
|
| 801 |
+
val_auc_py = None if (val_auc is None or val_auc < 0) else float(val_auc)
|
| 802 |
+
val_f1_py = float(val_f1)
|
| 803 |
+
test_auc_py = None if test_auc is None else float(test_auc)
|
| 804 |
+
test_f1_py = float(test_f1)
|
| 805 |
+
|
| 806 |
+
# best_val_key = (method, k_base_name, k, label)
|
| 807 |
+
selection_py = None
|
| 808 |
+
if best_val_key is not None:
|
| 809 |
+
selection_py = [
|
| 810 |
+
None if best_val_key[0] is None else str(best_val_key[0]),
|
| 811 |
+
None if best_val_key[1] is None else str(best_val_key[1]),
|
| 812 |
+
None if best_val_key[2] is None else int(best_val_key[2]),
|
| 813 |
+
None if best_val_key[3] is None else str(best_val_key[3]),
|
| 814 |
+
]
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
# ---- Explainability (best-effort)
|
| 818 |
+
run_id = uuid.uuid4().hex
|
| 819 |
+
|
| 820 |
+
if best_pack["selector"] is not None:
|
| 821 |
+
X_train_aligned = X_train_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0)
|
| 822 |
+
X_val_aligned = X_val_proc.reindex(columns=best_pack["pre_features"], fill_value=0.0)
|
| 823 |
+
Xtr_sel_final = pd.DataFrame(best_pack["selector"].transform(X_train_aligned), columns=best_pack["final_features"])
|
| 824 |
+
Xv_sel_final = pd.DataFrame(best_pack["selector"].transform(X_val_aligned), columns=best_pack["final_features"])
|
| 825 |
+
else:
|
| 826 |
+
Xtr_sel_final = X_train_proc[best_pack["final_features"]]
|
| 827 |
+
Xv_sel_final = X_val_proc[best_pack["final_features"]]
|
| 828 |
+
|
| 829 |
+
explain_relpath = None
|
| 830 |
+
explain_type = None
|
| 831 |
+
feature_importances = None
|
| 832 |
+
pretty_names = _pretty_feature_names(best_pack["final_features"])
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
_emit(90, "Building explainability plot...")
|
| 836 |
+
shap_relpath = _make_shap_plot_if_possible(
|
| 837 |
+
model=best_pack["model"], X_bg=Xtr_sel_final, X_eval=Xv_sel_final,
|
| 838 |
+
feature_names=pretty_names, run_id=run_id,
|
| 839 |
+
)
|
| 840 |
+
if shap_relpath:
|
| 841 |
+
explain_relpath = shap_relpath
|
| 842 |
+
explain_type = "shap"
|
| 843 |
+
|
| 844 |
+
# Also compute mean absolute SHAP values (top features) to store in summary
|
| 845 |
+
try:
|
| 846 |
+
import shap
|
| 847 |
+
explainer = shap.Explainer(best_pack["model"], Xtr_sel_final)
|
| 848 |
+
sv = explainer(Xv_sel_final)
|
| 849 |
+
vals = np.abs(sv.values).mean(0)
|
| 850 |
+
feature_importances = [(str(f), float(v)) for f, v in zip(pretty_names, vals)]
|
| 851 |
+
|
| 852 |
+
except Exception:
|
| 853 |
+
feature_importances = None
|
| 854 |
+
|
| 855 |
+
else:
|
| 856 |
+
perm_relpath = _make_perm_plot_if_possible(
|
| 857 |
+
model=best_pack["model"], X_eval=Xv_sel_final, y_eval=y_val,
|
| 858 |
+
feature_names=pretty_names, run_id=run_id,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
if perm_relpath:
|
| 862 |
+
explain_relpath = perm_relpath
|
| 863 |
+
explain_type = "permutation"
|
| 864 |
+
|
| 865 |
+
# Also compute permutation importances numerically for the summary
|
| 866 |
+
try:
|
| 867 |
+
res_pi = permutation_importance(
|
| 868 |
+
best_pack["model"], Xv_sel_final, y_val,
|
| 869 |
+
n_repeats=10, random_state=0, scoring="roc_auc"
|
| 870 |
+
)
|
| 871 |
+
feature_importances = [(str(f), float(s)) for f, s in zip(pretty_names, res_pi.importances_mean)]
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
except Exception:
|
| 875 |
+
feature_importances = None
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
artifact = {
|
| 879 |
+
"model": best_pack["model"],
|
| 880 |
+
"selector": best_pack["selector"],
|
| 881 |
+
"preprocessor": best_pack["preprocessor"],
|
| 882 |
+
"pre_selection_feature_names": best_pack["pre_features"],
|
| 883 |
+
"final_feature_names": best_pack["final_features"],
|
| 884 |
+
"feature_method": best_pack["feature_method"],
|
| 885 |
+
"k_from": best_pack["k_from"],
|
| 886 |
+
"k": int(best_pack["k"]), # ensure plain int
|
| 887 |
+
"shap_relpath": shap_relpath,
|
| 888 |
+
"scaler_type": best_pack["scaler_type"],
|
| 889 |
+
"ensemble_type": best_pack["ensemble"],
|
| 890 |
+
"base_models": best_pack["base_models"],
|
| 891 |
+
"meta_learner": best_pack["meta_learner"],
|
| 892 |
+
"voting_type": best_pack["voting_type"],
|
| 893 |
+
"balancing_method": best_pack["balancing"],
|
| 894 |
+
"augmentation": best_pack["augmentation"],
|
| 895 |
+
"explain_relpath": explain_relpath,
|
| 896 |
+
"explain_type": explain_type,
|
| 897 |
+
"target_samples": target_samples,
|
| 898 |
+
"val_auc": val_auc_py,
|
| 899 |
+
"val_f1": val_f1_py,
|
| 900 |
+
"test_auc": test_auc_py,
|
| 901 |
+
"test_f1": test_f1_py,}
|
| 902 |
+
|
| 903 |
+
summary_raw = {
|
| 904 |
+
"selection": selection_py, # list not tuple, already py types
|
| 905 |
+
"ensemble": artifact["ensemble_type"],
|
| 906 |
+
"base_models": artifact["base_models"],
|
| 907 |
+
"meta_learner": artifact["meta_learner"],
|
| 908 |
+
"voting_type": artifact["voting_type"],
|
| 909 |
+
"balancing": artifact["balancing_method"],
|
| 910 |
+
"augmentation": artifact["augmentation"],
|
| 911 |
+
"scaler": artifact["scaler_type"],
|
| 912 |
+
"explain_type": explain_type,
|
| 913 |
+
"target_samples": artifact["target_samples"],
|
| 914 |
+
"k": int(best_pack["k"]),
|
| 915 |
+
"k_from": best_pack["k_from"],
|
| 916 |
+
"feature_method": best_pack["feature_method"],
|
| 917 |
+
# NEW: numeric importances so results_view/_extract_top_taxa can build NCBI links
|
| 918 |
+
"permutation_importance": feature_importances if explain_type == "permutation" else None,
|
| 919 |
+
"shap_importance": feature_importances if explain_type == "shap" else None,
|
| 920 |
+
}
|
| 921 |
+
|
| 922 |
+
summary_py = _json_safe(summary_raw)
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
saved = None
|
| 926 |
+
if save_to:
|
| 927 |
+
joblib.dump(artifact, save_to)
|
| 928 |
+
saved = save_to
|
| 929 |
+
|
| 930 |
+
_emit(100, "Done")
|
| 931 |
+
return TrainResult(
|
| 932 |
+
val_auc=val_auc_py,
|
| 933 |
+
val_f1=val_f1_py,
|
| 934 |
+
test_auc=test_auc_py,
|
| 935 |
+
test_f1=test_f1_py,
|
| 936 |
+
shap_relpath=explain_relpath,
|
| 937 |
+
summary=summary_py,
|
| 938 |
+
model_path=saved,
|
| 939 |
+
artifact=artifact,
|
| 940 |
+
)
|