Spaces:
Sleeping
Sleeping
File size: 2,514 Bytes
f89d715 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | import os
import gradio as gr
import joblib
import numpy as np
from sklearn.datasets import load_iris
# Tải thông tin nhãn lớp Iris
iris = load_iris()
target_names = iris.target_names
# Kiểm tra sự tồn tại của mô hình
model_path = "model.pkl"
if os.path.exists(model_path):
model = joblib.load(model_path)
else:
model = None
def predict(sepal_length, sepal_width, petal_length, petal_width):
if model is None:
return "Không tìm thấy tệp model.pkl. Vui lòng huấn luyện mô hình trước!", {}
# Tạo mảng đặc trưng cho đầu vào
features = np.array(
[[sepal_length, sepal_width, petal_length, petal_width]]
)
# Dự đoán lớp và tính toán xác suất
prediction = model.predict(features)[0]
probabilities = model.predict_proba(features)[0]
class_name = target_names[prediction].upper()
# Tạo từ điển chứa xác suất của từng loài hoa
prob_dict = {
target_names[i].capitalize(): float(probabilities[i]) for i in range(3)
}
return class_name, prob_dict
# Xây dựng giao diện Gradio
demo = gr.Interface(
fn=predict,
inputs=[
gr.Slider(
minimum=float(iris.data[:, 0].min()),
maximum=float(iris.data[:, 0].max()),
value=5.1,
label="Sepal Length (cm)",
),
gr.Slider(
minimum=float(iris.data[:, 1].min()),
maximum=float(iris.data[:, 1].max()),
value=3.5,
label="Sepal Width (cm)",
),
gr.Slider(
minimum=float(iris.data[:, 2].min()),
maximum=float(iris.data[:, 2].max()),
value=1.4,
label="Petal Length (cm)",
),
gr.Slider(
minimum=float(iris.data[:, 3].min()),
maximum=float(iris.data[:, 3].max()),
value=0.2,
label="Petal Width (cm)",
),
],
outputs=[
gr.Textbox(label="Loài hoa dự đoán (Predicted Species)"),
gr.Label(num_top_classes=3, label="Xác suất chi tiết (Probabilities)"),
],
title="🌸 Iris Species Classification Predictor",
description="Ứng dụng ML nhỏ dự đoán loài hoa Iris, được huấn luyện và triển khai tự động qua quy trình CI/CD GitHub Actions lên Gradio SDK của Hugging Face Spaces.",
theme="soft",
)
# Chỉ chạy launch khi gọi trực tiếp file này
if __name__ == "__main__":
demo.launch()
|