You built an ML with TensorFlow or Sci-kit learn and now want it deployed on a website. This article is a quick guide on loading an ML model in Python and using it to make predictions on a web app with Flask. This is based on my image classifier app found on my GitHub Fabio-RibeiroB/image_classifier_app: App to classify happy or sad images (github.com). In this app, the user uploads a file and presses predict. Specifically, the user uploads images for binary classification. It all depends on your model. You can change this code to upload CSV data instead, for example.
I appreciate this article is high-level and lacking detail. It is more than an outline to make it as short-form as possible. To see more, check out my aforementioned repo on GitHub. Anyway, let’s begin.
Save and Load
Let’s say you have a Sequential model that you compiled.
model = Sequential()
....some model
....
model.compile(....)
Now save the model, for example, as a .h5 file. I saved mine in a “models” folder. You can also use pickle to dump and load models as .pkl files.
from tensorflow.keras.models import load_model
import os
model.save(os.path.join('models','model.h5'))
Now load it in your Flask app.
from flask import Flask, render_template, request, redirect, flash, session # useful flask modules
from werkzeug.utils import secure_filename # security
import logging
logging.basicConfig(level=logging.DEBUG)
logging.info('program starting')
from tensorflow.keras.models import load_model
model = load_model('models/model.h5') # loaded model
Static Uploads Folder
We also need a folder where we can upload data for the model. Make a directory called static, and within that, a directory called uploads.
UPLOAD_FOLDER = './static/uploads'
ALLOWED_EXTENSIONS = {'png', 'jgp', 'jpeg'} # change depending on model
app = Flask(__name__)
app.secret_key = b'somesecretkey'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
"""
Check the uploaded data is correct format
""""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
Routes and Prediction
Now I create the necessary routes in your app that makes a prediction. We will later make a home.html will allow us to start a prediction. The predict.html page shows the results.
@app.route('/')
def home():
return render_template('home.html')
@app.route('/predict', methods=['POST'])
def predict():
file = request.files('file')
# check uploaded file is okay in upload folder
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
data_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file. save(data_path) # save data
# read data in for example with pandas
prediction = model.predict(data) # in my example prediction is one number, a probability.
# remember to delete file after use
os.remove(data_path)
return render_template('predict.html', data=prediction)
if __name__ == "__main__":
app.run(debug=True)
The above code saves the valid data in the uploads folder and loads the data. For example, you could load your data into a pandas data frame. The /predict route passes the prediction variable containing a single prediction. The prediction variable is passed to predict.html to render the result on the web page. If your model outputs a lot of predictions, like a CSV of predictions, these lines will need to be modified. You probably want the user to download the predictions as a CSV instead of displaying the results on the screen. In this case, you need a download button in your HTML.
However, continuing my example, we have a home page called home.html with a form for the user to upload data. I simply removed the rest of my HTML tags to declutter the code snippet below. See my repo for the entire HTML file.
In home.html
<form method="POST" action="{{url_for('home')}}" enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=predict>
</form>
And now for prediction.html. This page will simply output the results with a back button.
{{data}}
<form>
<input type="button" value="Try again" on click="history.back()">
</form>
Flask run, and the app should be running in local host.
Sprunki Incredibox brings fresh beats and visuals to the beloved music-mixing formula, making creativity even more engaging. For more fun, check out Clicker Games!
This article brilliantly touches on AI’s growing role in creative workflows. Tools like Lovart are pushing boundaries by blending human intent with smart automation, making design more intuitive than ever.
Roulette’s probability is fascinating, isn’t it? Seeing platforms like 68wim casino cater to Vietnamese players with easy registration & secure funding is great. It’s all about balancing risk & reward! Definitely a fun space to explore.
Interesting read! The shift towards seamless online experiences is key – especially with integrated options like GCash. Exploring platforms like jl boss com shows how far Philippine online gaming has come. Definitely a future-focused approach!
Scratch cards are all about that quick thrill, right? It’s fun to think of gaming as a strategy contest like ph987 casino describes – not just luck! Secure platforms & smart onboarding (like verifying accounts) are key for peace of mind too. Great post!
That’s a solid point about team dynamics! Seeing how bonuses & rewards can boost a player’s strategy reminds me of jljl77 app download – maximizing value is key in any competitive scene, right? Great article!
Really interesting read! It’s cool seeing how online platforms like phswerte blend tradition with modern gaming – that verification step feels important for building trust, and a secure experience is key!
Interesting take! Seeing platforms like 777pinas login really focus on the Filipino market is smart. Secure verification is key for trust – a solid foundation for any online experience, especially with博彩 platforms! 👍
Dice games are fascinating – the math behind them is surprisingly complex! Seeing platforms like jljl77 2025 online casino embrace innovation with secure logins & PHP support is great for Filipino players. It’s exciting to see gaming evolve!
That jungle theme at SS777 is really clever – makes the experience more engaging! Easy deposits with GCash & PayMaya are a huge plus. Thinking of checking out their slots – anyone tried the ss777 slot download? Seems like a fun way to unwind!
Interesting read! Tracking patterns in baccarat can be insightful, especially with tools offering real-time stats. I’ve been checking out spintime legit – their approach to data-driven gaming is pretty unique for Filipino players. Definitely worth a look!
Forza Real Betis! Love my team, and this realbetis site is clutch for keeping up with everything. Let’s go Betis, let’s win! Check out Real Betis! realbetis
Been playing at XSino Casino for a while now, and I gotta say, it’s pretty good. Games are solid, and withdrawals are quick. Definitely worth checking out, you too can check them out at xsino. Also, their support rocks!. and if you like the whole shebang, go to XSino Casino
Casino LeoVegas is my absolute favorite! The mobile app is smooth, and I love their exclusive games. Always a good time on LeoVegas , check it at casinoleovegas.
I really appreciate the customer support here. They helped me fix my login issue in minutes. Five stars for jili123casinologin.
The graphics are top notch and the gameplay is just addictive. I’ve won a couple of times already today! Check out phperyaplus if you want some real excitement.
It really felt like my lucky day when I joined this site. The graphics are great and the gameplay is very addictive. Five stars from me! luckyday33
If you are looking for a reliable betting site, this is it. The odds are competitive and the site layout is very clean. My go-to is idtmbet88
I was skeptical at first but this platform is legit. The customer service is very helpful and the withdrawal process is quick. Give krmmwin a try if you want a reliable site.
Really impressed with the customer support here. They helped me sort out my account in minutes. idselayar88 is definitely my new favorite spot for gaming.
The best spot to track and play on current events. Very intuitive layout and the community is great. Glad I found phpolymarket!
Super love the interface here. It is very easy to navigate and the bonuses are actually helpful for new players. Highly recommended! ph688jili
Such a fun place to spend some free time. The game selection is huge and the rewards are actually attainable. Big shout out to bd9777game.
Setting up my account took less than two minutes. The navigation is intuitive and I didn’t get lost at all. idsersanbet is top notch.
I love the layout and the overall vibe of this site. It feels professional and trustworthy. I am spending a lot of my free time on idasia128 lately.
The VIP perks are a game changer. It makes playing feel much more rewarding and exclusive. vipjililogin
Easy access and no hassle at all. I appreciate how straightforward the site is without all the unnecessary clutter. jili988login is a winner.
The graphics are top notch and the gameplay is super addictive. I really appreciate how easy it is to navigate the menu here. You should try ph6jili if you want some real action.
Found xjilicc through a friend and I am glad I did. The payouts are fair and the customer support is actually helpful. A solid choice for gaming enthusiasts.
I’ve been playing here for a while now and the withdrawal process is surprisingly fast. Definitely one of the most reliable platforms I’ve found recently. Check out vnhn88 for a great experience.
The app version is just perfect. I can play anywhere and the loading time is almost zero. Very convenient for daily gaming! jili666app
The VIP treatment here is actually real. I feel like a valued player and the rewards keep coming. If you want a premium feel, head over to vipphlogin.
The game variety here is insane! I love how fast the payouts are processed. Highly recommend nbajjecasino to anyone looking for some real excitement.
Finally found a place where the bonuses actually make sense. Had a great run last night and the interface is very user-friendly. Check out g7777casino if you want some real action.
Finding a working link can be a pain but this one is perfect. I got straight into the action without any issues. Thanks lisboa77link.
I’ve tried a few platforms lately and this one is surprisingly smooth. The login process is fast and I didn’t run into any lag. Definitely a solid choice for anyone looking for a reliable spot. Check out mawinbetlogin for a great experience!
Super reliable platform with a great selection of slots. I appreciate how transparent everything is with the withdrawals. Love phjili999
The APK works perfectly on my Android phone. No lags and the gameplay is seamless. Great job on phlwinapk.
Really impressed with the security and transparency of this platform. It feels safe to deposit and play here. Trust phbunos88
Solid platform with a great community. I’ve had a few big wins here and the withdrawal process was surprisingly quick. Keep it up bdxbajee31!
Love the variety of games here. It keeps things exciting and I’ve already won a few times this week. Give daulatgame777 a go if you like high energy gaming.
Top notch service and very responsive pages. I appreciate the transparency and the fair play rules here. Big thanks to idarena39.
Finally found a site that actually treats players right. Great variety of options and the customer support is top notch. Highly recommend idayam11
Love the variety of games they have here. It feels like a real casino vibe from the comfort of my home. Definitely give tayahotcasino a shot if you want some excitement.
Really appreciate the customer support here. They helped me out quickly. Great vibes at phjili49!
Logging in is so quick and the site doesn’t lag at all. I love how easy it is to manage my account here. winjiliphlogin is the way to go.
Very professional setup and the withdrawal process is transparent. No hidden fees which is a huge plus. Cheers to idmonata189.
The login process is super fast and I have not encountered any bugs so far. It is great to see a site that values user experience. Give bd66zzlogin a try.
This place has a great vibe and the payouts are consistently fast. I appreciate the transparency and the easy registration process. phbtbjili
Great selection of games and the payouts are handled very efficiently. I trust this site for my leisure time. Check out bigobet899 if you want a fair game.
The APK installation was a breeze. Everything works perfectly on my Android phone. Get your plus777downloadapk here.
I’ve had some crazy wins here recently! The excitement is real and the atmosphere is just right for gaming. I’m addicted to x8888slot now.
Really impressed with the withdrawal speed here. It is rare to find a site that pays out this quickly. Truly trust jili98login with my deposits.
The variety of games here is insane. I spent the whole weekend exploring and everything works perfectly on my phone. br80gamesvip is definitely my new favorite spot.