Deploy Model Machine Learning

Galih Setiawan Nurohim
3 min readJul 2, 2024

--

langkah-langkah untuk membuat model regresi linear sederhana menggunakan Scikit-Learn, menyimpan model dengan `joblib`, dan kemudian mengekspornya.

Langkah 1: Instalasi Library yang Dibutuhkan

Pastikan Anda menginstal Scikit-Learn dan Joblib. Jika belum, Anda bisa menginstalnya menggunakan pip:

pip install scikit-learn joblib

Langkah 2: Buat dan Latih Model Regresi Linear

Buat skrip Python untuk membuat dan melatih model regresi linear.

import numpy as np
from sklearn.linear_model import LinearRegression
import joblib

# Buat data contoh
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])

# Inisialisasi dan latih model regresi linear
model = LinearRegression()
model.fit(X, y)

# Simpan model menggunakan joblib
joblib.dump(model, 'linear_regression_model.pkl')

print("Model berhasil disimpan sebagai 'linear_regression_model.pkl'")

Langkah 3: Memuat Model yang Disimpan

Buat skrip Python untuk memuat model yang telah disimpan dan melakukan prediksi.

import joblib
import numpy as np

# Muat model yang telah disimpan
model = joblib.load('linear_regression_model.pkl')

# Buat data untuk prediksi
X_new = np.array([[6], [7], [8]])

# Prediksi menggunakan model yang dimuat
predictions = model.predict(X_new)

print("Prediksi untuk X_new:", predictions)

Langkah 4: Deploy Model dengan Flask

Sekarang kita akan membuat API menggunakan Flask untuk mendepoloy model ini.

a. Buat Folder Proyek

Buat folder proyek dengan struktur berikut:

my_project/
├── app.py
├── linear_regression_model.pkl
├── templates/
│ └── index.html
├── static/
└── script.css
└── style.js

b. Buat Flask Script (`app.py`)

Buat file `app.py` di folder proyek dan tuliskan kode berikut:

from flask import Flask, request, jsonify, render_template
import joblib
import numpy as np

# Buat instance Flask
app = Flask(__name__)

# Muat model yang telah disimpan
model = joblib.load('linear_regression_model.pkl')

@app.route('/')
def home():
return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
try:
# Ambil data dari request
data = request.json
# Misalkan data dikirim dalam bentuk JSON: {"input": [1.5, 2.5, 3.5]}
input_data = np.array(data['input']).reshape(-1, 1)

# Buat prediksi menggunakan model
predictions = model.predict(input_data)

# Kembalikan hasil prediksi sebagai JSON
return jsonify({'predictions': predictions.tolist()})

except Exception as e:
return jsonify({'error': str(e)})

if __name__ == '__main__':
app.run(debug=True)

c. Buat Halaman HTML (`templates/index.html`)

Buat file `index.html` di folder `templates`:

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Prediksi Regresi Linear</title>
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<div class="container">
<h1>Prediksi Regresi Linear</h1>
<form id="prediction-form">
<label for="input">Masukkan nilai (dipisahkan dengan koma):</label>
<input type="text" id="input" name="input" />
<button type="submit">Prediksi</button>
</form>
<h2>Prediksi:</h2>
<ul id="predictions-list"></ul>
</div>
<script src="/static/script.js"></script>
</body>
</html>

d. Buat JavaScript File (`static/script.js`)

Buat file `script.js` di folder `static`:

document.getElementById('prediction-form').addEventListener('submit', function(event) {
event.preventDefault();

const inputField = document.getElementById('input');
const inputValues = inputField.value.split(',').map(Number);

fetch('/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ input: inputValues })
})
.then(response => response.json())
.then(data => {
const predictionsList = document.getElementById('predictions-list');
predictionsList.innerHTML = '';
if (data.predictions) {
data.predictions.forEach(prediction => {
const li = document.createElement('li');
li.textContent = prediction;
predictionsList.appendChild(li);
});
} else if (data.error) {
const li = document.createElement('li');
li.textContent = `Error: ${data.error}`;
predictionsList.appendChild(li);
}
})
.catch(error => console.error('Error:', error));
});

Buat file `style.css` di folder `static`:

/* static/style.css */

body {
font-family: Arial, sans-serif;
background-color: #f0f2f5;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
color: #333;
}

.container {
background: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
max-width: 400px;
width: 100%;
text-align: center;
}

h1 {
color: #2c3e50;
margin-bottom: 20px;
}

form {
display: flex;
flex-direction: column;
}

label {
text-align: left;
margin-bottom: 8px;
font-weight: bold;
font-size: 14px;
}

input {
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
width: calc(100% - 22px);
}

button {
padding: 10px 15px;
background-color: #3498db;
color: #ffffff;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
margin-bottom: 20px;
}

button:hover {
background-color: #2980b9;
}

h2 {
color: #2c3e50;
margin-bottom: 10px;
}

ul {
list-style-type: none;
padding: 0;
text-align: left;
}

li {
background: #e7f3fe;
padding: 10px;
margin-bottom: 8px;
border-radius: 4px;
border-left: 5px solid #3498db;
}

Langkah 5: Jalankan Aplikasi

Jalankan aplikasi Flask Anda dengan perintah berikut di terminal:

python app.py

Sekarang Anda bisa membuka browser dan mengakses `http://127.0.0.1:5000` untuk melihat antarmuka pengguna. Anda bisa memasukkan nilai-nilai input (dipisahkan dengan koma), dan hasil prediksi akan ditampilkan di bawah formulir.

Dengan langkah-langkah di atas, Anda dapat membuat model regresi linear sederhana, menyimpan model dengan `joblib`, dan mendepoloy API berbasis Flask serta antarmuka pengguna untuk berinteraksi dengan model prediksi yang telah disimpan.

--

--