{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "xCJgSqhgHYLU", "outputId": "19465b47-9bf0-4325-adeb-36cf7668e711" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 1.0\n", "Classification Report:\n", " precision recall f1-score support\n", "\n", " 0 1.00 1.00 1.00 3\n", "\n", " accuracy 1.00 3\n", " macro avg 1.00 1.00 1.00 3\n", "weighted avg 1.00 1.00 1.00 3\n", "\n", "Churn (1=yes, 0=no): 1\n" ] } ], "source": [ "# Logistic Regression Example: Predicting Churn\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.metrics import accuracy_score, classification_report\n", "\n", "# Example dataset (binary churn: 1 = churn, 0 = stay)\n", "data = {\n", " 'age': [25, 32, 47, 51, 62, 23, 38, 44, 29, 55],\n", " 'monthly_spend': [50, 60, 120, 110, 150, 40, 75, 95, 52, 130],\n", " 'tenure_months': [12, 24, 36, 48, 60, 6, 18, 30, 20, 50],\n", " 'churn': [0, 0, 1, 1, 1, 0, 0, 1, 0, 1] # target variable\n", "}\n", "\n", "df = pd.DataFrame(data)\n", "\n", "# Features (X) and target (y)\n", "X = df[['age', 'monthly_spend', 'tenure_months']]\n", "y = df['churn']\n", "\n", "# Split into train/test sets\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n", "\n", "# Initialize and train logistic regression model\n", "model = LogisticRegression()\n", "model.fit(X_train, y_train)\n", "\n", "# Predictions\n", "y_pred = model.predict(X_test)\n", "\n", "# Evaluation\n", "print(\"Accuracy:\", accuracy_score(y_test, y_pred))\n", "print(\"Classification Report:\\n\", classification_report(y_test, y_pred))\n", "\n", "# Example: predict churn for a new customer\n", "new_customer_data = [[30, 1000, 12]] # age=30, monthly_spend=70, tenure=12 months\n", "new_customer_df = pd.DataFrame(new_customer_data, columns=X.columns)\n", "prediction = model.predict(new_customer_df)\n", "print(\"Churn (1=yes, 0=no):\", prediction[0])" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.12/dist-packages/huggingface_hub/utils/_auth.py:104: UserWarning: \n", "Error while fetching `HF_TOKEN` secret value from your vault: 'Requesting secret HF_TOKEN timed out. Secrets can only be fetched when running from the Colab UI.'.\n", "You are not authenticated with the Hugging Face Hub in this notebook.\n", "If the error persists, please let us know by opening an issue on GitHub (https://github.com/huggingface/huggingface_hub/issues/new).\n", " warnings.warn(\n" ] } ], "source": [ "from huggingface_hub import notebook_login\n", "\n", "notebook_login()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "5KSqmEhWJ-rI", "outputId": "6c82578c-1825-4bd2-91ef-50f5f806f718" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model saved locally: /content/ML_LogisticRegression_ChurnPredictor.joblib\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "85a30be4a1f44ae79523ee54c0357b21", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Processing Files (0 / 0) : | | 0.00B / 0.00B " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "641a2182b8654e6199826f326bbd030a", "version_major": 2, "version_minor": 0 }, "text/plain": [ "New Data Upload : | | 0.00B / 0.00B " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "604857563a91403aa3500a3f09aaab4d", "version_major": 2, "version_minor": 0 }, "text/plain": [ " ...ion_ChurnPredictor.joblib: 100%|##########| 1.18kB / 1.18kB " ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "Uploaded model to https://huggingface.co/looh2/model\n" ] } ], "source": [ "import joblib\n", "from pathlib import Path\n", "from huggingface_hub import HfApi\n", "\n", "# Define local model path and target Hugging Face repo\n", "repo_id = \"looh2/model\"\n", "model_path = Path(\"ML_LogisticRegression_ChurnPredictor.joblib\")\n", "\n", "# Save the trained model locally\n", "joblib.dump(model, model_path)\n", "print(f\"Model saved locally: {model_path.resolve()}\")\n", "\n", "# Create repo if needed, then upload model artifact\n", "api = HfApi()\n", "api.create_repo(repo_id=repo_id, repo_type=\"model\", exist_ok=True)\n", "api.upload_file(\n", " path_or_fileobj=str(model_path),\n", " path_in_repo=model_path.name,\n", " repo_id=repo_id,\n", " repo_type=\"model\",\n", ")\n", "\n", "print(f\"Uploaded model to https://huggingface.co/{repo_id}\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4QkIQGpEKCRB", "outputId": "ecf2df81-0095-488d-adfb-daad96d1b3f5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "FastAPI application defined. To run it, save this code as a Python file (e.g., main.py) and execute `uvicorn main:app --reload` in your terminal.\n", "For example, you can then test the /predict endpoint with a POST request like this (using requests library):\n", "\n", "import requests\n", "import json\n", "\n", "url = \"http://127.0.0.1:8000/predict\"\n", "headers = {'Content-Type': 'application/json'}\n", "data = {\"age\": 30, \"monthly_spend\": 1000, \"tenure_months\": 12}\n", "\n", "response = requests.post(url, headers=headers, data=json.dumps(data))\n", "print(response.json())\n", "\n" ] } ], "source": [ "import joblib\n", "from fastapi import FastAPI\n", "from pydantic import BaseModel\n", "import uvicorn\n", "import pandas as pd\n", "from contextlib import asynccontextmanager\n", "\n", "# --- FastAPI Example Endpoint ---\n", "\n", "# Global variables to store the model and feature columns\n", "loaded_model = None\n", "feature_columns = None\n", "\n", "# Define a Pydantic model for input data\n", "class CustomerFeatures(BaseModel):\n", " age: int\n", " monthly_spend: float\n", " tenure_months: int\n", "\n", "# Define lifespan events for FastAPI application\n", "@asynccontextmanager\n", "async def lifespan(app: FastAPI):\n", " global loaded_model\n", " global feature_columns\n", " # The model is expected to be saved by a previous step.\n", " # This ensures the API loads an existing model at startup.\n", " model_filename = 'model_logistic_regression.pkl'\n", " loaded_model = joblib.load(model_filename)\n", "\n", " # Assuming X.columns was available from an earlier execution for feature order.\n", " # If 'X' is not globally available when the API starts, you might need to hardcode feature_columns\n", " # or load them from a separate file saved alongside the model.\n", " # For this example, we'll use the feature names from the previous notebook state.\n", " feature_columns = ['age', 'monthly_spend', 'tenure_months']\n", " print(\"Model loaded successfully for FastAPI.\")\n", " yield\n", " # Clean up (optional) - e.g., close database connections\n", " print(\"FastAPI application shutdown.\")\n", "\n", "app = FastAPI(lifespan=lifespan)\n", "\n", "@app.post(\"/predict\")\n", "async def predict_churn(customer: CustomerFeatures):\n", " # Convert input data to a DataFrame, ensuring correct column order\n", " input_data = pd.DataFrame([customer.dict()])\n", " input_data = input_data[feature_columns] # Reorder columns to match training data\n", "\n", " prediction = loaded_model.predict(input_data)[0]\n", " probability = loaded_model.predict_proba(input_data)[0].tolist()\n", "\n", " return {\n", " \"prediction\": int(prediction),\n", " \"probability_stay\": probability[0], # Probability of class 0 (stay)\n", " \"probability_churn\": probability[1] # Probability of class 1 (churn)\n", " }\n", "\n", "@app.get(\"/\")\n", "async def read_root():\n", " return {\"message\": \"Welcome to the Churn Prediction API! Use /predict to get predictions.\"}\n", "\n", "print(\"FastAPI application defined. To run it, save this code as a Python file (e.g., main.py) and execute `uvicorn main:app --reload` in your terminal.\")\n", "print(\"For example, you can then test the /predict endpoint with a POST request like this (using requests library):\")\n", "print(\"\"\"\n", "import requests\n", "import json\n", "\n", "url = \"http://127.0.0.1:8000/predict\"\n", "headers = {'Content-Type': 'application/json'}\n", "data = {\"age\": 30, \"monthly_spend\": 1000, \"tenure_months\": 12}\n", "\n", "response = requests.post(url, headers=headers, data=json.dumps(data))\n", "print(response.json())\n", "\"\"\")" ] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }