{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Ibrahim Salami",
  "title_listed": "My Model Worked Perfectly. Then I Tried to Make It Useful.",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/my-model-worked-perfectly-then-i-tried-to-make-it-useful/",
  "publish_date": "2026-09-03",
  "corpus_stage": "",
  "notes": "",
  "id": "4a2609e653a0",
  "collected_at": "2026-10-02T11:21:53",
  "title": "My Model Worked Perfectly. Then I Tried to Make It Useful. | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# My Model Worked Perfectly. Then I Tried to Make It Useful.\nTurning a trained churn classifier into a FastAPI service that other software can actually call.\n[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\nSeptember 3, 202611 min read\n![](../images/000.jpg)\nGenerated with Gemini AI\nFastAPI churn classifier API\nA few months ago, I tried to challenge myself to undertake a journey to transition from a data analytics background to data engineering. So far I’ve built a total of two impactful real-world projects that actually taught me something useful. I built a GitHub ETL pipeline that extracts GitHub repositories and loads them into a SQLite database — this ran on a schedule using GitHub Actions. I also built an RSS pipeline that extracts articles from RSS feeds and stores them into a Kestra database — orchestrated by Kestra to run on an hourly schedule.\nNow that I’ve understood ETL to a point, I wanted to try something new. I wanted to keep practicing all I’ve learned in the past whilst building something new. I had always been fascinated by the field of machine learning, but never actually had the courage to step in because I thought it had complex math. Not anymore. \nRecently, I built a churn prediction model for a fictional telecom company I am calling Northline Mobile (P.S. I’m using a fictional company because I understand things best with real-world scenarios). I provided it with data from 7043 customers, telling it whether they had signed up for a 1-year contract or month-to-month plans, length of customer, monthly charges, add-ons, etc. Furthermore, I told it who eventually left Northline Mobile. I cross-validated the model with customers it had not seen yet.\nIt achieved 81% accuracy. This taught me everything that goes into building a model. Obviously I didn’t understand all the complex code, because I prefer intuitive drag and drop interfaces rather than complex code. But I understood the essential building blocks of building a model; I’ll explain further below with a simplified architecture.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\nSo building this model felt like a win from a machine learning perspective; my model worked.\nBut there was still one problem: it was still not really useful.\nAssuming a Northline employee who needed a prediction comes to me, I would have to open Jupyter, load the right notebook, run the cells in the correct order and make a manual call to predict_churn(). Yeah, the model exists, but I was the only one that knows how to use it. No one else at Northline could just send information on a customer to the model and retrieve a prediction and it could not speak to any other application either.\nThis article will be covering this.\nI recently learned that there is a difference between **having a model** and **having a service**.\nIf a model just sits in a notebook only the person who built it can use it. But making it a service makes it possible for everyone to use it, other teams, apps, dashboards and systems that do not need to know or care how the prediction is made.\nIt turns out building the machine learning model was the easiest part, but making it useful is another crucial element worth exploring.\n## **What \"Done\" Meant Before the API**\nHere's roughly what building the model looked like:\n![](../images/001.jpg)\nThat’s pretty much it. Nothing too fancy.\nBy the end of that, I had a trained churn classifier, a preprocessing pipeline that cleaned and encoded the raw data, and evaluation numbers I was comfortable with (more on those numbers shortly, they're not perfect and I'm not going to pretend they are). \nBut like I said. Assuming Northline's retention team builds a dashboard, and they want it to flag at-risk customers automatically. Their dashboard can't reasonably open my Jupyter notebook and run my cells. It needs something else entirely. Something like this:\n![](../images/body-e38190796effb4220dfc.jpg)\nThat's the shift this article covers. One quick disclaimer, though: this isn’t a FastAPI tutorial. FastAPI is simply the tool I happened to use to expose the model as a service. The interesting part, at least for me, was figuring out what that service should actually look like. \n## **The Boundary I Actually Needed**\nThe real question wasn't \"how do I put FastAPI around my model.\" It was \"what should the boundary between my software and my model actually look like.\"\nI had two options. Full fidelity or something more simplified that only involves training the model on a handful of data. I settled on full fidelity: this means that the API accepts every raw field Northline's other systems would realistically have about a customer, the same columns as the original dataset, not some simplified subset. A request would typically look like this:\njson\n\n```\n{\n\n  \"gender\": \"Female\",\n\n  \"SeniorCitizen\": 0,\n\n  \"Partner\": \"Yes\",\n\n  \"Dependents\": \"No\",\n\n  \"tenure\": 12,\n\n  \"PhoneService\": \"Yes\",\n\n  \"MultipleLines\": \"No\",\n\n  \"InternetService\": \"Fiber optic\",\n\n  \"OnlineSecurity\": \"No\",\n\n  \"OnlineBackup\": \"Yes\",\n\n  \"DeviceProtection\": \"No\",\n\n  \"TechSupport\": \"No\",\n\n  \"StreamingTV\": \"Yes\",\n\n  \"StreamingMovies\": \"No\",\n\n  \"Contract\": \"Month-to-month\",\n\n  \"PaperlessBilling\": \"Yes\",\n\n  \"PaymentMethod\": \"Electronic check\",\n\n  \"MonthlyCharges\": 75.5,\n\n  \"TotalCharges\": 890.5\n\n}\n```\n\nAnd the response is deliberately small:\njson\n\n```\n{\n\n  \"churn_probability\": 0.3136,\n\n  \"prediction\": 0,\n\n  \"risk_level\": \"Medium\"\n\n}\n```\n\nI have to point out something real quick though. That risk_level field isn't something the model produces. The model only outputs a raw probability. But a raw 0.31 isn't something a retention rep can act on at a glance, so I added a simple bucket: below 0.3 is Low, 0.3 to 0.6 is Medium, above that is High. Those thresholds are a starting guess, not something I derived statistically, and I want to be upfront about that rather than pretend they're more rigorous than they are.\nThis is the boundary. Input schema, output schema, what's required, what's rejected. Once I'd actually thought this through, the endpoint itself was almost the easy part.\n## **Preparing the Model for Life Outside the Notebook**\nThere's a step between \"request arrives\" and \"prediction comes back\" that's easy to underestimate: the raw JSON coming in looks nothing like what the model actually expects. Here’s what the journey typically looks like:\n![](../images/body-fa7fe893b13043d35314.jpg)\nIt’s worth keeping in mind that the API can't invent its own version of preprocessing. Whatever happened to the data during training has to happen, identically, at inference time. For instance, if training scales tenure and MonthlyCharges a certain way, and the API scales them differently, or forgets to scale them at all, the model is being handed numbers it's never seen the shape of before. But the fascinating thing is that it won't give you an error, it'll just quietly guess wrong.\nSo to prevent this issue, I built one `preprocessing.py`, imported by both the training script and the live API.\n![](../images/body-03049b95ac33f1a595a7.jpg)\nThere's a specific bug this caught, however. My binary-encoding function looked like this during training:\npython\n\n```\nbinary_cols = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling', 'Churn']\n\nfor col in binary_cols:\n\n    df[col] = df[col].map({'Yes': 1, 'No': 0})\n```\n\nThat's fine when training, because the training data has a Churn column, the actual answer. But a live request obviously doesn't have Churn in it. That's what we're trying to predict. Running this function unmodified against a request would crash looking for a column that was never going to exist. The fix was small, just check the column's actually present first, but it's exactly the kind of thing that only shows up once you try to run training-time code at inference time.\n## **Building the FastAPI Layer**\nHere's how the project ended up structured:\nplaintext\n\n```\nchurn-api/\n\n├── data/\n\n├── notebooks/\n\n│   └── 01_eda.ipynb\n\n├── app/\n\n│   ├── main.py\n\n│   ├── schemas.py\n\n│   ├── model.py\n\n│   └── preprocessing.py\n\n├── models/\n\n│   ├── churn_pipeline.pkl\n\n│   ├── scaler.pkl\n\n│   └── feature_columns.pkl\n\n├── train.py\n\n└── requirements.txt\n```\n\nTwo things are worth explaining about this layout. First, `train.py` lives at the project root, outside app/. app/ is specifically the code that runs the live service. Training isn't part of the service, it's a separate process that produces the artifacts the service depends on. Second, `train.py` reaches into app/ to reuse `preprocessing.py`, not the other way around. The service doesn't know or care how it was trained. It just needs the same preprocessing logic.\n## **Loading the Model Once**\nOne decision that seems obvious in hindsight but wasn't something I thought about until I nearly got it wrong: where do you load the model?\nThe wrong way is loading it inside the /predict function itself, so every single request reads the .pkl files off disk again. That's slow, and it's wasteful for no reason.\nThe right way is loading it once, when the module is first imported:\npython\n\n```\n# app/model.py\n\nimport joblib\n\nfrom pathlib import Path\n\nMODEL_DIR = Path(__file__).resolve().parent.parent / \"models\"\n\nmodel = joblib.load(MODELDIR / \"churn_pipeline.pkl\")\n\nscaler = joblib.load(MODELDIR / \"scaler.pkl\")\n\nfeaturecolumns = joblib.load(MODEL_DIR / \"feature_columns.pkl\")\n```\n\nBy the time the API is actually serving requests, the model is already sitting in memory, ready to go. This is a small detail, but it's the difference between an API you built and an API you built like it's actually going to be result = predict_churn(customer.model_dump()) return resultused.\n## **Designing /predict**\nWith the model loaded once and preprocessing shared with training, the actual endpoint ended up small:\npython\n\n```\n# app/main.py\n\nfrom fastapi import FastAPI\n\nfrom schemas import CustomerRequest, ChurnPrediction\n\nfrom model import predict_churn\n\napp = FastAPI(title=\"Northline Mobile Churn API\")\n\n@app.post(\"/predict\", response_model=ChurnPrediction)\n\ndef predict(customer: CustomerRequest):\n\n```\n\nThat smallness is intentional. All the actual logic, preprocessing, loading, prediction, lives in `model.py` and `preprocessing.py`. The route function's only job is to receive a validated request and hand it off. I didn't want business logic creeping into what should be pure HTTP plumbing.\nBehind that route, `predict_churn` runs the request through the same steps training used, including one detail that took me a minute to understand: a single request can only ever produce one value per one-hot encoded category. Training data might generate four PaymentMethod dummy columns across thousands of rows, but one customer's request can only be one payment method. So before prediction, I reindex the request's columns against the exact list the model was trained on, filling anything missing with zero:\npython\n\n```\ndf = df.reindex(columns=_feature_columns, fill_value=0)\n```\n\nWithout that, a single request's column layout wouldn't reliably match what the model expects, and scikit-learn would either error or silently misalign features. This is the sort of detail that never shows up when you're testing on a full dataset, only when you send the model exactly one row at a time.\n## **Testing It Like Software**\nGetting a 200 OK in Swagger UI wasn't the finish line I thought it'd be. The more interesting question was what happens when the input isn't clean.\nI sent a request with tenure missing entirely. The API rejected it before the model ever saw it:\njson\n\n```\n{\n\n  \"detail\": [\n\n    {\n\n      \"type\": \"missing\",\n\n      \"loc\": [\"body\", \"tenure\"],\n\n      \"msg\": \"Field required\"\n\n    }\n\n  ]\n\n}\n```\n\nI sent \"gender\": \"female\", lowercase, instead of the expected \"Female\". Rejected again, with the exact reason:\njson\n\n```\n{\n\n  \"detail\": [\n\n    {\n\n      \"type\": \"literal_error\",\n\n      \"loc\": [\"body\", \"gender\"],\n\n      \"msg\": \"Input should be 'Male' or 'Female'\"\n\n    }\n\n  ]\n\n}\n```\n\nNeither of these ever reached predict_churn(). That's the point. The schema isn't just documentation, it's an actual gate. Bad input gets a clear, specific error back, not a confusing model failure three layers deep, and not a silently wrong prediction because the model tried to make sense of something it was never trained to see.\n## **When It Finally Felt Like Software**\nBefore, getting a prediction meant:\npython\n\n```\nmodel.predict(data)\n```\n\nwith Jupyter open, the right cells run in order, the right variables still sitting in memory from earlier in the session.\nNow it's `POST /predict`from anywhere. A curl command in a terminal. A request from a different application entirely. Someone who has never seen my code, never installed pandas, never heard of scikit-learn, can still get a churn prediction out of this model. That's the actual transformation. The model didn't get any smarter. It became something other software could use.\n## **What Still Isn't Solved**\nHere's the honest part. Sure, the model works and the API works. But it only works on my laptop.\nIf a Northline engineer tried to run this exact project on their own machine, there's no guarantee it would work. Maybe their Python version is different. Maybe they don't have Anaconda installed the way I do. Maybe a package version mismatch breaks something silently. Right now, \"it runs\" is really shorthand for \"it runs on my machine, under my specific setup, and I'm not fully sure which parts of that setup actually matter.\"\nThere's also no way to run this in the cloud yet. It's not reachable by anyone outside my own network. If my laptop is off, the API is off.\nI'm not solving any of that here. That's genuinely the next article. What I wanted to nail down first was making sure the application itself, the boundary, the contract, the validation, was solid before adding infrastructure on top of it. Adding Docker and a cloud deployment to something with a shaky foundation just means the shaky part is now harder to debug.\n## **What I Learned**\n  * **A working model isn't automatically a usable one.**  \nGood evaluation metrics tell me the model learned something useful. They don't tell me that someone else can actually send it data and get a prediction back. Turning a model into something people can use requires another layer of engineering.\n  * **The API is a contract, not just a wrapper.**  \nI initially thought the API would mostly be a thin layer around the model. In practice, deciding what a request should contain, what the API should reject, and what it should return turned out to be just as important as calling the model itself.\n  * **Inference is its own engineering problem.**  \nGetting a model to predict inside a notebook is relatively straightforward. Making those predictions reliably through an API introduces a different set of concerns. Preprocessing has to match training exactly, the model should be loaded once rather than for every request, and even something as simple as how a single request is shaped can matter.\n  * **Building locally first exposed the real problems early.**  \nThe Churn column bug, the reindexing issue, and even the convergence warning I ran into during training had nothing to do with the cloud. They were problems in the application itself. Finding them locally was much better than discovering them after adding Docker, EC2, and a deployment environment on top.\n  * **A clear boundary makes deployment easier later.**  \nI don't know exactly what Part 2 will throw at me once deployment enters the picture. But I do know that the application has a clear shape now: data comes in, it gets validated and prepared, the model makes a prediction, and a structured response goes back out. Whatever breaks next, at least it won't be because I never defined what the API was supposed to do.\n\n\n## **Now I Had a New Problem**\nI started this article because the model worked but wasn't useful. By the end, it's useful, at least to me. Anyone on my own machine, hitting localhost:8000, can get a real prediction back, complete with validation that catches bad input before it ever reaches the model.\nBut that's still the whole limitation. My laptop is the only place this exists.\nIn the next part, I'm taking this exact service and putting it inside a container, then deploying it to AWS. A few assumptions that have been invisible this whole time, about my environment, my file paths, and my local Python setup are about to become impossible to ignore.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-542334df68a32cd56c4a.jpeg)\nWritten By\n## [Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[See all from Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[Data Engineering](https://towardsdatascience.com/tag/data-engineering/)[Fastapi](https://towardsdatascience.com/tag/fastapi/)[Mlops](https://towardsdatascience.com/tag/mlops/)[Model Deployment](https://towardsdatascience.com/tag/model-deployment/)[Programming](https://towardsdatascience.com/tag/programming/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F&title=My%20Model%20Worked%20Perfectly.%20Then%20I%20Tried%20to%20Make%20It%20Useful.)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F&title=My%20Model%20Worked%20Perfectly.%20Then%20I%20Tried%20to%20Make%20It%20Useful.)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F&text=My%20Model%20Worked%20Perfectly.%20Then%20I%20Tried%20to%20Make%20It%20Useful.)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.jpeg)](https://towardsdatascience.com/how-to-speedup-your-pandas-code-by-10x-79a61c509c8b/)\n## [How to Speedup your Pandas Code by 10x](https://towardsdatascience.com/how-to-speedup-your-pandas-code-by-10x-79a61c509c8b/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFooled you! The trick is getting out of Pandas\n[Peter Grant](https://towardsdatascience.com/author/petergrant-81989/)\nFebruary 22, 20204 min read\n  * [![](../images/003.jpeg)](https://towardsdatascience.com/pinterests-visual-lens-how-computer-vision-explores-your-taste-5470f87502ad/)\n## [Pinterest's Visual Lens: How computer vision explores your taste](https://towardsdatascience.com/pinterests-visual-lens-how-computer-vision-explores-your-taste-5470f87502ad/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe science behind personalized visual recommendations\n[James Le](https://towardsdatascience.com/author/le-james94/)\nJanuary 24, 201813 min read\n  * [![](../images/004.jpg)](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/)\n## [Domain Adaptation: Fine-Tune Pre-Trained NLP Models](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA step-by-step guide to fine-tuning pre-trained NLP models for any domain\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nJuly 4, 20238 min read\n  * [![](../images/005.jpg)](https://towardsdatascience.com/how-to-build-an-elt-with-python-8f5d9d75a12e/)\n## [How to Build an ELT with Python](https://towardsdatascience.com/how-to-build-an-elt-with-python-8f5d9d75a12e/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nExtracting, Loading and Transforming Data\n[Marie Truong](https://towardsdatascience.com/author/marietruong/)\nFebruary 7, 20237 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/step-by-step-guide-to-time-series-visualization-using-plotnine-3a2306aeafe0/)\n## [Step-by-Step Guide to Time Series Visualization Using Plotnine](https://towardsdatascience.com/step-by-step-guide-to-time-series-visualization-using-plotnine-3a2306aeafe0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n6 graphics to explore your time series\n[Vitor Cerqueira](https://towardsdatascience.com/author/vcerq/)\nMarch 27, 20246 min read\n  * [![](../images/007.jpeg)](https://towardsdatascience.com/practical-data-visualization-guide-seaborn-vs-ggplot2-9747d9153ade/)\n## [Practical Data Visualization Guide: Seaborn vs Ggplot2](https://towardsdatascience.com/practical-data-visualization-guide-seaborn-vs-ggplot2-9747d9153ade/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHands-on tutorial with examples\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJanuary 8, 20214 min read\n  * [![](../images/008.png)](https://towardsdatascience.com/6-things-about-data-science-that-employers-dont-want-you-to-know-a659a9de06e4/)\n## [6 Things About Data Science that Employers Don't Want You to Know](https://towardsdatascience.com/6-things-about-data-science-that-employers-dont-want-you-to-know-a659a9de06e4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nBut you should definitely know about them\n[Terence Shin, MSc, MBA](https://towardsdatascience.com/author/terenceshin/)\nNovember 12, 20207 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/feature-selection-and-eda-in-python-c6c4eb1058a3/)\n## [Feature Selection and EDA in Machine Learning](https://towardsdatascience.com/feature-selection-and-eda-in-python-c6c4eb1058a3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to Use Data Visualization to Guide Feature Selection\n[Destin Gong](https://towardsdatascience.com/author/destingong/)\nMay 24, 202110 min read\n  * [![](../images/010.jpeg)](https://towardsdatascience.com/python3-12-98245ecd6a97/)\n## [What to Expect in Python 3.12](https://towardsdatascience.com/python3-12-98245ecd6a97/)\n[Programming](https://towardsdatascience.com/category/programming/)\nNew features, updates and removals in the upcoming Python 3.12 release\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nJanuary 4, 20236 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "My Model Worked Perfectly. Then I Tried to Make It Useful. | Towards Data Science",
    "description": "Turning a trained churn classifier into a FastAPI service that other software can actually call.",
    "keywords": null,
    "author": "Ibrahim Salami",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "My Model Worked Perfectly. Then I Tried to Make It Useful.",
    "og:description": "Turning a trained churn classifier into a FastAPI service that other software can actually call.",
    "og:url": "https://towardsdatascience.com/my-model-worked-perfectly-then-i-tried-to-make-it-useful/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/1788084041405_ighu7h.jpg",
    "og:image:width": "985",
    "og:image:height": "537",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Ibrahim Salami",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2026-09-03T15:30:01.837Z",
    "article:modified_time": "2026-09-03T15:30:01.837Z",
    "article:author": "https://towardsdatascience.com/author/ibrahim.salami/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_000.txt",
      "chars": 515
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_001.txt",
      "chars": 83
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_002.txt",
      "chars": 158
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_003.txt",
      "chars": 277
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_004.txt",
      "chars": 285
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_005.txt",
      "chars": 278
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_006.txt",
      "chars": 56
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_007.txt",
      "chars": 130
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_008.txt",
      "chars": 156
    },
    {
      "language": "txt",
      "file": "attachments/4a2609e653a0/code/block_009.txt",
      "chars": 20
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:56:53Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:56:53Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:56:53Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:56:53Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ibrahim.salami/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-engineering/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/fastapi/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/mlops/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/model-deployment/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-speedup-your-pandas-code-by-10x-79a61c509c8b/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/petergrant-81989/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/pinterests-visual-lens-how-computer-vision-explores-your-taste-5470f87502ad/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/le-james94/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/shashank kapadia/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=My+Model+Worked+Perfectly.+Then+I+Tried+to+Make+It+Useful.&u=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=My+Model+Worked+Perfectly.+Then+I+Tried+to+Make+It+Useful.&url=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=My+Model+Worked+Perfectly.+Then+I+Tried+to+Make+It+Useful.&url=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:29:27Z",
  "source_url": "https://towardsdatascience.com/my-model-worked-perfectly-then-i-tried-to-make-it-useful/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# My Model Worked Perfectly. Then I Tried to Make It Useful.\nTurning a trained churn classifier into a FastAPI service that other software can actually call.\n[Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\nSeptember 3, 202611 min read\n![](https://assets.insightmediagroup.io/media/1788084041405_ighu7h.jpg)\nGenerated with Gemini AI\nFastAPI churn classifier API\nA few months ago, I tried to challenge myself to undertake a journey to transition from a data analytics background to data engineering. So far I’ve built a total of two impactful real-world projects that actually taught me something useful. I built a GitHub ETL pipeline that extracts GitHub repositories and loads them into a SQLite database — this ran on a schedule using GitHub Actions. I also built an RSS pipeline that extracts articles from RSS feeds and stores them into a Kestra database — orchestrated by Kestra to run on an hourly schedule.\nNow that I’ve understood ETL to a point, I wanted to try something new. I wanted to keep practicing all I’ve learned in the past whilst building something new. I had always been fascinated by the field of machine learning, but never actually had the courage to step in because I thought it had complex math. Not anymore. \nRecently, I built a churn prediction model for a fictional telecom company I am calling Northline Mobile (P.S. I’m using a fictional company because I understand things best with real-world scenarios). I provided it with data from 7043 customers, telling it whether they had signed up for a 1-year contract or month-to-month plans, length of customer, monthly charges, add-ons, etc. Furthermore, I told it who eventually left Northline Mobile. I cross-validated the model with customers it had not seen yet.\nIt achieved 81% accuracy. This taught me everything that goes into building a model. Obviously I didn’t understand all the complex code, because I prefer intuitive drag and drop interfaces rather than complex code. But I understood the essential building blocks of building a model; I’ll explain further below with a simplified architecture.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\nSo building this model felt like a win from a machine learning perspective; my model worked.\nBut there was still one problem: it was still not really useful.\nAssuming a Northline employee who needed a prediction comes to me, I would have to open Jupyter, load the right notebook, run the cells in the correct order and make a manual call to predict_churn(). Yeah, the model exists, but I was the only one that knows how to use it. No one else at Northline could just send information on a customer to the model and retrieve a prediction and it could not speak to any other application either.\nThis article will be covering this.\nI recently learned that there is a difference between **having a model** and **having a service**.\nIf a model just sits in a notebook only the person who built it can use it. But making it a service makes it possible for everyone to use it, other teams, apps, dashboards and systems that do not need to know or care how the prediction is made.\nIt turns out building the machine learning model was the easiest part, but making it useful is another crucial element worth exploring.\n## **What \"Done\" Meant Before the API**\nHere's roughly what building the model looked like:\n![](https://assets.insightmediagroup.io/media/1788082113073_22jg2i.jpg)\nThat’s pretty much it. Nothing too fancy.\nBy the end of that, I had a trained churn classifier, a preprocessing pipeline that cleaned and encoded the raw data, and evaluation numbers I was comfortable with (more on those numbers shortly, they're not perfect and I'm not going to pretend they are). \nBut like I said. Assuming Northline's retention team builds a dashboard, and they want it to flag at-risk customers automatically. Their dashboard can't reasonably open my Jupyter notebook and run my cells. It needs something else entirely. Something like this:\n![](https://assets.insightmediagroup.io/media/1788082274166_72c6eo.jpg)\nThat's the shift this article covers. One quick disclaimer, though: this isn’t a FastAPI tutorial. FastAPI is simply the tool I happened to use to expose the model as a service. The interesting part, at least for me, was figuring out what that service should actually look like. \n## **The Boundary I Actually Needed**\nThe real question wasn't \"how do I put FastAPI around my model.\" It was \"what should the boundary between my software and my model actually look like.\"\nI had two options. Full fidelity or something more simplified that only involves training the model on a handful of data. I settled on full fidelity: this means that the API accepts every raw field Northline's other systems would realistically have about a customer, the same columns as the original dataset, not some simplified subset. A request would typically look like this:\njson\n\n```\n{\n\n  \"gender\": \"Female\",\n\n  \"SeniorCitizen\": 0,\n\n  \"Partner\": \"Yes\",\n\n  \"Dependents\": \"No\",\n\n  \"tenure\": 12,\n\n  \"PhoneService\": \"Yes\",\n\n  \"MultipleLines\": \"No\",\n\n  \"InternetService\": \"Fiber optic\",\n\n  \"OnlineSecurity\": \"No\",\n\n  \"OnlineBackup\": \"Yes\",\n\n  \"DeviceProtection\": \"No\",\n\n  \"TechSupport\": \"No\",\n\n  \"StreamingTV\": \"Yes\",\n\n  \"StreamingMovies\": \"No\",\n\n  \"Contract\": \"Month-to-month\",\n\n  \"PaperlessBilling\": \"Yes\",\n\n  \"PaymentMethod\": \"Electronic check\",\n\n  \"MonthlyCharges\": 75.5,\n\n  \"TotalCharges\": 890.5\n\n}\n```\n\nAnd the response is deliberately small:\njson\n\n```\n{\n\n  \"churn_probability\": 0.3136,\n\n  \"prediction\": 0,\n\n  \"risk_level\": \"Medium\"\n\n}\n```\n\nI have to point out something real quick though. That risk_level field isn't something the model produces. The model only outputs a raw probability. But a raw 0.31 isn't something a retention rep can act on at a glance, so I added a simple bucket: below 0.3 is Low, 0.3 to 0.6 is Medium, above that is High. Those thresholds are a starting guess, not something I derived statistically, and I want to be upfront about that rather than pretend they're more rigorous than they are.\nThis is the boundary. Input schema, output schema, what's required, what's rejected. Once I'd actually thought this through, the endpoint itself was almost the easy part.\n## **Preparing the Model for Life Outside the Notebook**\nThere's a step between \"request arrives\" and \"prediction comes back\" that's easy to underestimate: the raw JSON coming in looks nothing like what the model actually expects. Here’s what the journey typically looks like:\n![](https://assets.insightmediagroup.io/media/1788082666640_k25lsd.jpg)\nIt’s worth keeping in mind that the API can't invent its own version of preprocessing. Whatever happened to the data during training has to happen, identically, at inference time. For instance, if training scales tenure and MonthlyCharges a certain way, and the API scales them differently, or forgets to scale them at all, the model is being handed numbers it's never seen the shape of before. But the fascinating thing is that it won't give you an error, it'll just quietly guess wrong.\nSo to prevent this issue, I built one `preprocessing.py`, imported by both the training script and the live API.\n![](https://assets.insightmediagroup.io/media/1788082747892_9vnvne.jpg)\nThere's a specific bug this caught, however. My binary-encoding function looked like this during training:\npython\n\n```\nbinary_cols = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling', 'Churn']\n\nfor col in binary_cols:\n\n    df[col] = df[col].map({'Yes': 1, 'No': 0})\n```\n\nThat's fine when training, because the training data has a Churn column, the actual answer. But a live request obviously doesn't have Churn in it. That's what we're trying to predict. Running this function unmodified against a request would crash looking for a column that was never going to exist. The fix was small, just check the column's actually present first, but it's exactly the kind of thing that only shows up once you try to run training-time code at inference time.\n## **Building the FastAPI Layer**\nHere's how the project ended up structured:\nplaintext\n\n```\nchurn-api/\n\n├── data/\n\n├── notebooks/\n\n│   └── 01_eda.ipynb\n\n├── app/\n\n│   ├── main.py\n\n│   ├── schemas.py\n\n│   ├── model.py\n\n│   └── preprocessing.py\n\n├── models/\n\n│   ├── churn_pipeline.pkl\n\n│   ├── scaler.pkl\n\n│   └── feature_columns.pkl\n\n├── train.py\n\n└── requirements.txt\n```\n\nTwo things are worth explaining about this layout. First, `train.py` lives at the project root, outside app/. app/ is specifically the code that runs the live service. Training isn't part of the service, it's a separate process that produces the artifacts the service depends on. Second, `train.py` reaches into app/ to reuse `preprocessing.py`, not the other way around. The service doesn't know or care how it was trained. It just needs the same preprocessing logic.\n## **Loading the Model Once**\nOne decision that seems obvious in hindsight but wasn't something I thought about until I nearly got it wrong: where do you load the model?\nThe wrong way is loading it inside the /predict function itself, so every single request reads the .pkl files off disk again. That's slow, and it's wasteful for no reason.\nThe right way is loading it once, when the module is first imported:\npython\n\n```\n# app/model.py\n\nimport joblib\n\nfrom pathlib import Path\n\nMODEL_DIR = Path(__file__).resolve().parent.parent / \"models\"\n\nmodel = joblib.load(MODELDIR / \"churn_pipeline.pkl\")\n\nscaler = joblib.load(MODELDIR / \"scaler.pkl\")\n\nfeaturecolumns = joblib.load(MODEL_DIR / \"feature_columns.pkl\")\n```\n\nBy the time the API is actually serving requests, the model is already sitting in memory, ready to go. This is a small detail, but it's the difference between an API you built and an API you built like it's actually going to be result = predict_churn(customer.model_dump()) return resultused.\n## **Designing /predict**\nWith the model loaded once and preprocessing shared with training, the actual endpoint ended up small:\npython\n\n```\n# app/main.py\n\nfrom fastapi import FastAPI\n\nfrom schemas import CustomerRequest, ChurnPrediction\n\nfrom model import predict_churn\n\napp = FastAPI(title=\"Northline Mobile Churn API\")\n\n@app.post(\"/predict\", response_model=ChurnPrediction)\n\ndef predict(customer: CustomerRequest):\n\n```\n\nThat smallness is intentional. All the actual logic, preprocessing, loading, prediction, lives in `model.py` and `preprocessing.py`. The route function's only job is to receive a validated request and hand it off. I didn't want business logic creeping into what should be pure HTTP plumbing.\nBehind that route, `predict_churn` runs the request through the same steps training used, including one detail that took me a minute to understand: a single request can only ever produce one value per one-hot encoded category. Training data might generate four PaymentMethod dummy columns across thousands of rows, but one customer's request can only be one payment method. So before prediction, I reindex the request's columns against the exact list the model was trained on, filling anything missing with zero:\npython\n\n```\ndf = df.reindex(columns=_feature_columns, fill_value=0)\n```\n\nWithout that, a single request's column layout wouldn't reliably match what the model expects, and scikit-learn would either error or silently misalign features. This is the sort of detail that never shows up when you're testing on a full dataset, only when you send the model exactly one row at a time.\n## **Testing It Like Software**\nGetting a 200 OK in Swagger UI wasn't the finish line I thought it'd be. The more interesting question was what happens when the input isn't clean.\nI sent a request with tenure missing entirely. The API rejected it before the model ever saw it:\njson\n\n```\n{\n\n  \"detail\": [\n\n    {\n\n      \"type\": \"missing\",\n\n      \"loc\": [\"body\", \"tenure\"],\n\n      \"msg\": \"Field required\"\n\n    }\n\n  ]\n\n}\n```\n\nI sent \"gender\": \"female\", lowercase, instead of the expected \"Female\". Rejected again, with the exact reason:\njson\n\n```\n{\n\n  \"detail\": [\n\n    {\n\n      \"type\": \"literal_error\",\n\n      \"loc\": [\"body\", \"gender\"],\n\n      \"msg\": \"Input should be 'Male' or 'Female'\"\n\n    }\n\n  ]\n\n}\n```\n\nNeither of these ever reached predict_churn(). That's the point. The schema isn't just documentation, it's an actual gate. Bad input gets a clear, specific error back, not a confusing model failure three layers deep, and not a silently wrong prediction because the model tried to make sense of something it was never trained to see.\n## **When It Finally Felt Like Software**\nBefore, getting a prediction meant:\npython\n\n```\nmodel.predict(data)\n```\n\nwith Jupyter open, the right cells run in order, the right variables still sitting in memory from earlier in the session.\nNow it's `POST /predict`from anywhere. A curl command in a terminal. A request from a different application entirely. Someone who has never seen my code, never installed pandas, never heard of scikit-learn, can still get a churn prediction out of this model. That's the actual transformation. The model didn't get any smarter. It became something other software could use.\n## **What Still Isn't Solved**\nHere's the honest part. Sure, the model works and the API works. But it only works on my laptop.\nIf a Northline engineer tried to run this exact project on their own machine, there's no guarantee it would work. Maybe their Python version is different. Maybe they don't have Anaconda installed the way I do. Maybe a package version mismatch breaks something silently. Right now, \"it runs\" is really shorthand for \"it runs on my machine, under my specific setup, and I'm not fully sure which parts of that setup actually matter.\"\nThere's also no way to run this in the cloud yet. It's not reachable by anyone outside my own network. If my laptop is off, the API is off.\nI'm not solving any of that here. That's genuinely the next article. What I wanted to nail down first was making sure the application itself, the boundary, the contract, the validation, was solid before adding infrastructure on top of it. Adding Docker and a cloud deployment to something with a shaky foundation just means the shaky part is now harder to debug.\n## **What I Learned**\n  * **A working model isn't automatically a usable one.**  \nGood evaluation metrics tell me the model learned something useful. They don't tell me that someone else can actually send it data and get a prediction back. Turning a model into something people can use requires another layer of engineering.\n  * **The API is a contract, not just a wrapper.**  \nI initially thought the API would mostly be a thin layer around the model. In practice, deciding what a request should contain, what the API should reject, and what it should return turned out to be just as important as calling the model itself.\n  * **Inference is its own engineering problem.**  \nGetting a model to predict inside a notebook is relatively straightforward. Making those predictions reliably through an API introduces a different set of concerns. Preprocessing has to match training exactly, the model should be loaded once rather than for every request, and even something as simple as how a single request is shaped can matter.\n  * **Building locally first exposed the real problems early.**  \nThe Churn column bug, the reindexing issue, and even the convergence warning I ran into during training had nothing to do with the cloud. They were problems in the application itself. Finding them locally was much better than discovering them after adding Docker, EC2, and a deployment environment on top.\n  * **A clear boundary makes deployment easier later.**  \nI don't know exactly what Part 2 will throw at me once deployment enters the picture. But I do know that the application has a clear shape now: data comes in, it gets validated and prepared, the model makes a prediction, and a structured response goes back out. Whatever breaks next, at least it won't be because I never defined what the API was supposed to do.\n\n\n## **Now I Had a New Problem**\nI started this article because the model worked but wasn't useful. By the end, it's useful, at least to me. Anyone on my own machine, hitting localhost:8000, can get a real prediction back, complete with validation that catches bad input before it ever reaches the model.\nBut that's still the whole limitation. My laptop is the only place this exists.\nIn the next part, I'm taking this exact service and putting it inside a container, then deploying it to AWS. A few assumptions that have been invisible this whole time, about my environment, my file paths, and my local Python setup are about to become impossible to ignore.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657709013_9ddcph.jpeg)\nWritten By\n## [Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[See all from Ibrahim Salami](https://towardsdatascience.com/author/ibrahim.salami/)\n[Data Engineering](https://towardsdatascience.com/tag/data-engineering/)[Fastapi](https://towardsdatascience.com/tag/fastapi/)[Mlops](https://towardsdatascience.com/tag/mlops/)[Model Deployment](https://towardsdatascience.com/tag/model-deployment/)[Programming](https://towardsdatascience.com/tag/programming/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F&title=My%20Model%20Worked%20Perfectly.%20Then%20I%20Tried%20to%20Make%20It%20Useful.)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F&title=My%20Model%20Worked%20Perfectly.%20Then%20I%20Tried%20to%20Make%20It%20Useful.)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fmy-model-worked-perfectly-then-i-tried-to-make-it-useful%2F&text=My%20Model%20Worked%20Perfectly.%20Then%20I%20Tried%20to%20Make%20It%20Useful.)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/02/1f4WG4tcaAEKJHmwA_rDuIQ-scaled.jpeg)](https://towardsdatascience.com/how-to-speedup-your-pandas-code-by-10x-79a61c509c8b/)\n## [How to Speedup your Pandas Code by 10x](https://towardsdatascience.com/how-to-speedup-your-pandas-code-by-10x-79a61c509c8b/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFooled you! The trick is getting out of Pandas\n[Peter Grant](https://towardsdatascience.com/author/petergrant-81989/)\nFebruary 22, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2018/01/19offlNxZqjH1tTxPBQRfjg.jpeg)](https://towardsdatascience.com/pinterests-visual-lens-how-computer-vision-explores-your-taste-5470f87502ad/)\n## [Pinterest's Visual Lens: How computer vision explores your taste](https://towardsdatascience.com/pinterests-visual-lens-how-computer-vision-explores-your-taste-5470f87502ad/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nThe science behind personalized visual recommendations\n[James Le](https://towardsdatascience.com/author/le-james94/)\nJanuary 24, 201813 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/Domain-adaptation.jpg)](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/)\n## [Domain Adaptation: Fine-Tune Pre-Trained NLP Models](https://towardsdatascience.com/domain-adaption-fine-tune-pre-trained-nlp-models-a06659ca6668/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA step-by-step guide to fine-tuning pre-trained NLP models for any domain\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nJuly 4, 20238 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/02/0zZqvAUUiS7iK0k89-scaled.jpg)](https://towardsdatascience.com/how-to-build-an-elt-with-python-8f5d9d75a12e/)\n## [How to Build an ELT with Python](https://towardsdatascience.com/how-to-build-an-elt-with-python-8f5d9d75a12e/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nExtracting, Loading and Transforming Data\n[Marie Truong](https://towardsdatascience.com/author/marietruong/)\nFebruary 7, 20237 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/03/0NEYU03U5INfWpTW3-scaled.jpg)](https://towardsdatascience.com/step-by-step-guide-to-time-series-visualization-using-plotnine-3a2306aeafe0/)\n## [Step-by-Step Guide to Time Series Visualization Using Plotnine](https://towardsdatascience.com/step-by-step-guide-to-time-series-visualization-using-plotnine-3a2306aeafe0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n6 graphics to explore your time series\n[Vitor Cerqueira](https://towardsdatascience.com/author/vcerq/)\nMarch 27, 20246 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0kwyjJjzFZVsm5zto-scaled.jpeg)](https://towardsdatascience.com/practical-data-visualization-guide-seaborn-vs-ggplot2-9747d9153ade/)\n## [Practical Data Visualization Guide: Seaborn vs Ggplot2](https://towardsdatascience.com/practical-data-visualization-guide-seaborn-vs-ggplot2-9747d9153ade/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nHands-on tutorial with examples\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nJanuary 8, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1aiPf7KhLotRM9OE4K7LD6w.png)](https://towardsdatascience.com/6-things-about-data-science-that-employers-dont-want-you-to-know-a659a9de06e4/)\n## [6 Things About Data Science that Employers Don't Want You to Know](https://towardsdatascience.com/6-things-about-data-science-that-employers-dont-want-you-to-know-a659a9de06e4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nBut you should definitely know about them\n[Terence Shin, MSc, MBA](https://towardsdatascience.com/author/terenceshin/)\nNovember 12, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/1o2T5RMUA-oXrjUN8h5rfcQ.png)](https://towardsdatascience.com/feature-selection-and-eda-in-python-c6c4eb1058a3/)\n## [Feature Selection and EDA in Machine Learning](https://towardsdatascience.com/feature-selection-and-eda-in-python-c6c4eb1058a3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to Use Data Visualization to Guide Feature Selection\n[Destin Gong](https://towardsdatascience.com/author/destingong/)\nMay 24, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/15UIxC5-70TnQNcK1a6PMWw-scaled.jpeg)](https://towardsdatascience.com/python3-12-98245ecd6a97/)\n## [What to Expect in Python 3.12](https://towardsdatascience.com/python3-12-98245ecd6a97/)\n[Programming](https://towardsdatascience.com/category/programming/)\nNew features, updates and removals in the upcoming Python 3.12 release\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nJanuary 4, 20236 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/4a2609e653a0/pages/",
  "body_markdown_path": "attachments/4a2609e653a0/pages/archived-body.md",
  "local_html": "attachments/4a2609e653a0/pages/archived-body.html",
  "body_source": "prior_capture"
}