farrah29 commited on
Commit
507fb5f
·
verified ·
1 Parent(s): 0b93569

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -65
app.py CHANGED
@@ -1,67 +1,36 @@
1
- from flask import Flask, request, jsonify
2
- import joblib
3
- import numpy as np
4
  import pandas as pd
5
 
6
- # Inisialisasi aplikasi Flask
7
- app = Flask(__name__)
8
-
9
- # Muat model yang telah dilatih
10
- model_filename = 'decision_tree_model.h5'
11
- model = joblib.load(model_filename)
12
-
13
- # Definisikan nama target dari dataset Iris
14
- # (sesuai dengan urutan dari dataset Scikit-learn)
15
- iris_target_names = ['setosa', 'versicolor', 'virginica']
16
- # Definisikan nama fitur untuk validasi
17
- feature_names = [
18
- 'sepal length (cm)',
19
- 'sepal width (cm)',
20
- 'petal length (cm)',
21
- 'petal width (cm)'
22
- ]
23
-
24
- @app.route('/')
25
- def home():
26
- return "<h1>API Klasifikasi Bunga Iris</h1><p>Gunakan endpoint /predict untuk membuat prediksi.</p>"
27
-
28
- @app.route('/predict', methods=['POST'])
29
- def predict():
30
- """
31
- Membuat prediksi spesies bunga Iris.
32
- Input harus berupa JSON dengan format:
33
- {
34
- "features": [5.1, 3.5, 1.4, 0.2]
35
- }
36
- Urutan fitur: sepal length, sepal width, petal length, petal width (dalam cm)
37
- """
38
- try:
39
- # Ambil data JSON dari request
40
- data = request.get_json()
41
-
42
- # Validasi input
43
- if 'features' not in data or not isinstance(data['features'], list) or len(data['features']) != 4:
44
- return jsonify({'error': 'Input tidak valid. Harap sediakan JSON dengan key "features" berisi list 4 angka.'}), 400
45
-
46
- features = np.array(data['features']).reshape(1, -1)
47
-
48
- # Buat DataFrame untuk memastikan nama fitur sesuai saat prediksi
49
- # Ini adalah praktik yang baik untuk menghindari error jika urutan fitur berubah
50
- features_df = pd.DataFrame(features, columns=feature_names)
51
-
52
- # Lakukan prediksi
53
- prediction_idx = model.predict(features_df)[0]
54
- predicted_class_name = iris_target_names[prediction_idx]
55
-
56
- # Kembalikan hasil prediksi dalam format JSON
57
- return jsonify({
58
- 'predicted_class': predicted_class_name,
59
- 'class_index': int(prediction_idx)
60
- })
61
-
62
- except Exception as e:
63
- return jsonify({'error': str(e)}), 500
64
-
65
- if __name__ == '__main__':
66
- # Jalankan aplikasi Flask (hanya untuk development lokal)
67
- app.run(debug=True, host='0.0.0.0', port=5000)
 
1
+ import gradio as gr
2
+ from sklearn.datasets import load_iris
3
+ from sklearn.tree import DecisionTreeClassifier
4
  import pandas as pd
5
 
6
+ # Load iris dataset
7
+ iris = load_iris()
8
+ X = pd.DataFrame(iris.data, columns=iris.feature_names)
9
+ y = iris.target
10
+
11
+ # Train model
12
+ model = DecisionTreeClassifier()
13
+ model.fit(X, y)
14
+
15
+ # Define prediction function
16
+ def predict_iris(sepal_length, sepal_width, petal_length, petal_width):
17
+ input_data = [[sepal_length, sepal_width, petal_length, petal_width]]
18
+ pred = model.predict(input_data)[0]
19
+ return iris.target_names[pred]
20
+
21
+ # Create Gradio interface
22
+ iface = gr.Interface(
23
+ fn=predict_iris,
24
+ inputs=[
25
+ gr.Number(label="Sepal Length (cm)"),
26
+ gr.Number(label="Sepal Width (cm)"),
27
+ gr.Number(label="Petal Length (cm)"),
28
+ gr.Number(label="Petal Width (cm)")
29
+ ],
30
+ outputs=gr.Text(label="Predicted Iris Species"),
31
+ title="Iris Flower Classification",
32
+ description="Klasifikasi bunga iris menggunakan Decision Tree."
33
+ )
34
+
35
+ if __name__ == "__main__":
36
+ iface.launch()