Zero Labs
Industry News / AI

I Swapped the ML Model in My Android App. The App Had No Idea.

Source · Towards AI By Vortana Say

From the publisher’s feed, collected in the ZeroLabs newsroom.

How interface-driven design makes model upgrades invisible to your Android codebase.FinRisk is a credit risk classifier android application that I built to explore on-device ML. The app runs entirely on-device. No server, no API, no internet. It takes three inputs: income, debt ratio, and credit score. These inputs decide whether to approve or flag a loan application in under 15 milliseconds on a phone.I copied one file, finrisk_classifier.tflite, into app/src/main/assets/, replacing the old one. Ran the app. Same LiteRtRiskClassifier. Same RiskAssessmentViewModel. Same UI. The model underneath had changed from logistic regression to a neural network. The Android code had not.This wasn’t luck. It was the payoff from a design decision I made before I ever thought I’d need to upgrade anything. The Python training script changed in seven places. The Android code changed in zero. This is what that looks like and why it happened.The problemThe logistic regression version handled most cases well. But one automated test I wrote to catch model failures kept returning the wrong answer. The model never sees raw dollar amounts or credit scores. During training, every feature is scaled to a value between 0 and 1. Income of $200K, the maximum in the dataset, becomes 1.0. A debt ratio of 80% stays 0.8 because it is already a proportion. A credit score of 850, the maximum possible, becomes 1.0.The Android app replicates this same scaling before passing inputs to the model, which is its own story. For verification purposes, [1.0, 0.8, 1.0] means the most extreme version of this applicant: maximum income, maximum credit, and 80% of that income already gone to debt. Expected result: DENY. Actual result: APPROVE, with a confidence score of 0.677.Any experienced loan officer flags this without hesitation. High income, yes. But 80% of it is already gone. The model could not see that.The reason is not a bug, and it cannot be fixed by training longer or collecting more data. Logistic regression is a weighted voting system. Each input feature casts an independent vote, and training learns how much weight each vote deserves. Income votes for approval. Credit score votes for approval. Debt ratio votes against, but gets outvoted two to one.The problem is that the features cannot talk to each other. Income cannot turn to Debt Ratio and say “given how high I am, your 80% is catastrophic.” Each feature contributes in isolation, with no awareness of the others. The decision boundary is a flat plane through the feature space. That plane can tilt toward high income or away from high debt, but it can never bend. It cannot carve out the specific corner where high income and high debt together signal danger. No amount of training changes this. It is a constraint baked into the architecture.The neural network removes that constraint by adding a hidden layer between the raw inputs and the final decision. Think of it as hiring a team of analysts who sit between the data and the loan officer’s desk. Before any individual feature reading reaches the decision point, these analysts recombine the raw inputs into new signals. One might learn to track disposable income after debt obligations. Another might learn to flag when debt load is high relative to the income bracket. These learned combinations, not the raw features, become the basis for the final call.On the same failing input, the neural network outputs 0.080 and confidently denies the application. The difference between 0.677 and 0.080 is not a marginal improvement. It is a fundamentally different capability.Swapping the architecture is the smallest part of the upgrade. Most tutorials stop there, which is why people are surprised when a model swap breaks things in unexpected places. There were seven changes in the Python training script.1. Model definitionThe logistic regression was a single Dense layer mapping three inputs directly to one sigmoid output, four parameters total. The neural network adds a hidden layer of eight ReLU neurons before that output layer, bringing the parameter count to 41.# Logistic regression: input goes directly to outputmodel = tf.keras.Sequential([ tf.keras.layers.Dense(units=1, activation='sigmoid', input_shape=(3,))])# Neural network: input passes through a hidden layer firstmodel = tf.keras.Sequential([ tf.keras.layers.Dense(units=8, activation='relu', input_shape=(3,), name='hidden_layer'), tf.keras.layers.Dense(units=1, activation='sigmoid', name='output_layer')])The output layer is identical. Sigmoid stays because binary classification requires a probability between 0 and 1, set by the problem type, not by design preference. The hidden layer uses ReLU, which passes positive values through unchanged and blocks negative ones. That asymmetry introduces the non-linearity that lets the boundary curve.Adding one hidden layer is all it takes to go from a line to a curve.2. Training dataThe architecture can learn feature interactions, but only if the training data contains a learnable signal. The original data used a weak interaction penalty for high-income, high-debt cases. That penalty was not strong enough to flip the label.The score dropped from 0.72 to 0.57, which is still above the approval threshold, so the training label still said APPROVE. The model cannot learn “this is risky” when the data says “this is safe.” Strengthening the penalty to negative 0.50 dropped that score to 0.22, producing an unambiguous DENY label. With roughly 200 examples now clearly labeled, the network had enough signal.The lesson here extends beyond this example: when a model upgrade fails in production, the first instinct is to reach for a bigger model. The right question is whether the training data actually contains the signal you are asking the model to learn.3. Training durationFour parameters converge around epoch 30. Forty-one parameters need 200 epochs. The loss landscape is more complex with more weights to tune, and gradient descent needs more steps to navigate it. Stopping at 50 epochs with the new architecture produces worse results than the old model on identical data, not because the architecture is wrong, but because it has not trained long enough.4. Validation strategyWith four parameters, Keras’s built-in validation_split is fine. With 41, a three-way explicit split matters more: 70% training, 15% validation, 15% held-out test. The held-out set is the honest final exam, data the model never sees during training or monitoring. When test accuracy is close to validation accuracy, the model is generalizing. When it is much lower, the model memorized the training data.5. InterpretabilityLogistic regression’s weights read like a sentence: income at positive 3.210, debt at negative 4.399, credit at positive 1.953. There is a direct line from each number to a human concept. The neural network’s hidden layer has 24 numbers connecting three inputs to eight neurons. Those numbers do not map to anything explainable to a stakeholder. You have traded transparency for the ability to learn interactions, and that trade is worth making here.6. The verification approachBecause individual weights no longer carry meaning, the verification function drops weight-direction checks entirely. The only verification that matters is behavioral: feed known inputs, confirm the outputs match what a domain expert would decide. The critical gate is whether input [1.0, 0.8, 1.0] produces DENY. This is the same shift Android engineers make when moving from unit tests that inspect internal state to integration tests that verify visible behavior. As systems grow more complex, the question shifts from “do the internals look right” to “does it do the right thing.”7. ReproducibilityLogistic regression has a convex loss function with one global minimum. Wherever gradient descent starts, it finds the same answer. Neural networks have a non-convex loss function with many local minima. Different starting points lead to different solutions, some of which learn the interaction pattern and some of which do not. Without seeding TensorFlow’s random number generator, the interaction test passes on some runs and fails on others with no code changes between runs.# Before: numpy seed was sufficientnp.random.seed(42)# After: TensorFlow needs its own seed for weight initializationnp.random.seed(42)tf.random.set_seed(42)One line. Completely silent when missing. The kind of thing that makes you wonder if you accidentally changed something you did not touch.Android sideThe complete list of Kotlin changes required to support the new model is nothing.LiteRtRiskClassifier, the class that wraps LiteRT (Google's runtime for running ML models directly on Android devices), loads whatever .tflite file lives in app/src/main/assets/. It does not know and does not care whether the model inside is logistic regression, a neural network, or something else. The input shape is still (3,). The output shape is still (1,). The inference logic is unchanged. RiskAssessmentViewModel calls classifier.assess(input) and gets a result. It has never known what model it is talking to.interface RiskClassifier { suspend fun assess(features: FloatArray): Result fun close()}When I replaced the file in assets, the ViewModel learned nothing about the upgrade because it had nothing to learn. The model grew from 1.8 KB to 2.6 KB. The Kotlin codebase grew by zero bytes.This worked because of a decision made before writing the first line of training code. The RiskClassifier interface separates the contract from the implementation. The contract says "take features, return a result." The implementation handles everything TFLite-specific.class LiteRtRiskClassifier @Inject constructor( private val context: Context) : RiskClassifier { // all TFLite details live here // the ViewModel never sees any of this}Hilt, Android’s dependency injection framework, injects whichever implementation is currently bound: LiteRtRiskClassifier in production, a deterministic mock in tests, FallbackRiskClassifier when the model fails to load on a low-memory device. When the model changes, only the .tflite file changes. The rest of the app is insulated from that change entirely.The ViewModel never knows which model is running. Hilt decides at injection time.Android engineers already know this intuition from other parts of the codebase. If your ViewModel directly instantiates a TFLite interpreter, every model upgrade touches the ViewModel, becomes a Kotlin change, becomes a test change, becomes a potential UI change. If your ViewModel depends on an interface and Hilt handles the binding, every model upgrade is a file copy. The scope of the change stays on the Python side, where the actual change happened.ConclusionBoth models were trained on identical data with the same random seeds and the same splits. The only variable was architecture.The accuracy improvement is real but modest. What the numbers do not show is that logistic regression is confidently wrong on the interaction case. A score of 0.677 is not borderline, it is a strong approval signal for an applicant that any practitioner would flag. The improvement is not in the average case. It is in a specific failure mode the previous model was architecturally incapable of handling.The architecture decision you make when first adding an ML feature to an Android app determines how expensive every subsequent change is. If inference is tightly coupled, if normalization constants are hardcoded next to the interpreter, if there is no abstraction between the app and whatever model is deployed, then every model change reaches into the UI layer. If inference is behind a clean interface, a model upgrade is operationally the same as updating a dependency version.The interface costs almost nothing to write upfront. The cost of not writing it shows up later, when you want to swap the model, add a fallback, or test inference in isolation without a real device.The full FinRisk source code, including Python training scripts and the complete Android app, is MIT licensed at github.com/vsay01/FinRisk. I go deeper on all seven training changes and the production hardening patterns in Machine Learning for Android Engineers.I Swapped the ML Model in My Android App. The App Had No Idea. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.