Build a full-stack ML web app with our step-by-step guide. Integrate ML models and web tech for quick, seamless deployment.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
pickle module is frequently used for this purpose.
// Example: Training and saving a scikit-learn model
import pickle
from sklearn.datasets import load\_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test\_split
// Load dataset
data = load\_iris()
X, y = data.data, data.target
// Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
// Create and train the model
model = RandomForestClassifier()
model.fit(X_train, y_train)
// Optionally evaluate your model here
accuracy = model.score(X_test, y_test)
print("Model accuracy:", accuracy)
// Save the model to a file
with open('ml\_model.pkl', 'wb') as file:
pickle.dump(model, file)
// Example: Flask API to serve the ML model
from flask import Flask, request, jsonify
import pickle
import numpy as np
app = Flask(**name**)
// Load the pre-trained model when the API starts
with open('ml\_model.pkl', 'rb') as file:
model = pickle.load(file)
// Define a prediction endpoint
@app.route('/predict', methods=['POST'])
def predict():
try:
// Retrieve JSON data
data = request.get\_json()
// Assume data contains feature values in a list under the key 'features'
features = data.get('features', [])
// Validate input
if not features or not isinstance(features, list):
return jsonify({'error': 'Invalid input format. Expected a list of feature values.'}), 400
// Convert features to numpy array and reshape it if needed (assuming the model requires 2D array)
input\_data = np.array(features).reshape(1, -1)
prediction = model.predict(input\_data)
// Return the prediction as JSON
return jsonify({'prediction': prediction.tolist()})
except Exception as e:
return jsonify({'error': str(e)}), 500
// Run the Flask application
if **name** == '**main**':
app.run(debug=True)
// Example: React component for prediction
import React, { useState } from 'react';
import axios from 'axios';
function PredictionForm() {
const [features, setFeatures] = useState('');
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
// Handle form submission
const handleSubmit = async (event) => {
event.preventDefault();
setError(null);
setResult(null);
// Process the comma-separated string into an array of numbers
const featureArray = features.split(',').map(item => parseFloat(item.trim()));
try {
// Call the /predict endpoint of the Flask API
const response = await axios.post('http://localhost:5000/predict', { features: featureArray });
setResult(response.data.prediction);
} catch (err) {
setError('Error fetching prediction. Please check the input and try again.');
}
};
return (
ML Model Prediction
{result && Prediction: {result}}
{error && Error: {error}}
);
}
export default PredictionForm;
// Example: Configuring CORS in Flask
from flask\_cors import CORS
app = Flask(**name**)
CORS(app, resources={r"/predict": {"origins": "http://your-react-app-domain.com"}})
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â