Update app.py
Browse files
app.py
CHANGED
@@ -8,92 +8,93 @@ from sklearn.preprocessing import StandardScaler
|
|
8 |
from sklearn.decomposition import PCA
|
9 |
from datasets import load_dataset
|
10 |
|
11 |
-
#
|
12 |
-
st.title("
|
13 |
|
14 |
-
#
|
15 |
-
with st.expander("
|
16 |
st.write(
|
17 |
-
"
|
18 |
-
"
|
19 |
-
"
|
20 |
-
"
|
21 |
)
|
22 |
|
23 |
-
#
|
24 |
-
uploaded_file = st.file_uploader("
|
25 |
|
26 |
-
#
|
27 |
-
if st.button("
|
28 |
dataset = load_dataset('kheejay88/country_data', split='train')
|
29 |
df = pd.DataFrame(dataset)
|
30 |
-
st.success("
|
31 |
|
32 |
-
|
|
|
33 |
st.write("""
|
34 |
-
**country** –
|
35 |
-
**child_mort** –
|
36 |
-
**exports** –
|
37 |
-
**health** –
|
38 |
-
**imports** –
|
39 |
-
**income** –
|
40 |
-
**inflation** –
|
41 |
-
**life_expec** –
|
42 |
-
**total_fer** –
|
43 |
-
**gdpp** – GDP
|
44 |
""")
|
45 |
|
46 |
if uploaded_file is not None:
|
47 |
df = pd.read_csv(uploaded_file)
|
48 |
|
49 |
if 'df' in locals():
|
50 |
-
#
|
51 |
categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
|
52 |
df.drop(columns=categorical_cols, inplace=True)
|
53 |
-
st.write("###
|
54 |
st.write(df.head())
|
55 |
|
56 |
-
#
|
57 |
scaler = StandardScaler()
|
58 |
scaled_data = scaler.fit_transform(df)
|
59 |
|
60 |
-
#
|
61 |
-
num_clusters = st.slider("
|
62 |
|
63 |
-
# K-Means
|
64 |
kmeans = KMeans(n_clusters=num_clusters, random_state=42)
|
65 |
clusters = kmeans.fit_predict(scaled_data)
|
66 |
-
df['
|
67 |
|
68 |
-
# PCA
|
69 |
pca = PCA(n_components=2)
|
70 |
pca_data = pca.fit_transform(scaled_data)
|
71 |
df['PCA1'] = pca_data[:, 0]
|
72 |
df['PCA2'] = pca_data[:, 1]
|
73 |
|
74 |
-
#
|
75 |
-
st.write("###
|
76 |
fig, ax = plt.subplots()
|
77 |
-
sns.scatterplot(x='PCA1', y='PCA2', hue='
|
78 |
st.pyplot(fig)
|
79 |
|
80 |
-
#
|
81 |
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
|
82 |
if len(numeric_cols) >= 2:
|
83 |
-
selected_col = st.selectbox("
|
84 |
-
st.write("###
|
85 |
fig, ax = plt.subplots()
|
86 |
-
for cluster in df['
|
87 |
-
cluster_data = df[df['
|
88 |
-
ax.plot(cluster_data.index, cluster_data[selected_col], label=f'
|
89 |
ax.legend()
|
90 |
st.pyplot(fig)
|
91 |
|
92 |
-
#
|
93 |
-
st.write("###
|
94 |
fig, ax = plt.subplots()
|
95 |
-
sns.countplot(x='
|
96 |
st.pyplot(fig)
|
97 |
|
98 |
-
st.markdown("---") #
|
99 |
-
st.markdown("**
|
|
|
8 |
from sklearn.decomposition import PCA
|
9 |
from datasets import load_dataset
|
10 |
|
11 |
+
# Tiêu đề ứng dụng
|
12 |
+
st.title("Ứng dụng Phân Cụm Dữ Liệu Không Giám Sát")
|
13 |
|
14 |
+
# Giới thiệu về ứng dụng
|
15 |
+
with st.expander("Giới thiệu về Ứng dụng"):
|
16 |
st.write(
|
17 |
+
"Ứng dụng này cho phép bạn tải lên bất kỳ loại tập dữ liệu không nhãn nào "
|
18 |
+
"và tự động phân cụm dữ liệu bằng thuật toán K-means. "
|
19 |
+
"Nó sẽ trực quan hóa các cụm bằng phương pháp PCA và cung cấp biểu đồ chuỗi thời gian cũng như phân phối cụm "
|
20 |
+
"giúp bạn nhận diện các mô hình và nhóm trong dữ liệu."
|
21 |
)
|
22 |
|
23 |
+
# Tải file
|
24 |
+
uploaded_file = st.file_uploader("Tải lên tập tin CSV", type=["csv"])
|
25 |
|
26 |
+
# Bộ dữ liệu mẫu
|
27 |
+
if st.button("Dùng thử với bộ dữ liệu mẫu"):
|
28 |
dataset = load_dataset('kheejay88/country_data', split='train')
|
29 |
df = pd.DataFrame(dataset)
|
30 |
+
st.success("Đã tải thành công bộ dữ liệu mẫu từ Hugging Face.")
|
31 |
|
32 |
+
# Cột dữ liệu
|
33 |
+
with st.expander("Các Cột Dữ Liệu"):
|
34 |
st.write("""
|
35 |
+
**country** – Tên quốc gia\n
|
36 |
+
**child_mort** – Tỷ lệ tử vong trẻ em dưới 5 tuổi trên 1000 ca sinh sống\n
|
37 |
+
**exports** – Xuất khẩu hàng hóa và dịch vụ trên đầu người (tính theo phần trăm GDP)\n
|
38 |
+
**health** – Chi tiêu y tế trên đầu người (tính theo phần trăm GDP)\n
|
39 |
+
**imports** – Nhập khẩu hàng hóa và dịch vụ trên đầu người (tính theo phần trăm GDP)\n
|
40 |
+
**income** – Thu nhập ròng trên đầu người\n
|
41 |
+
**inflation** – Tỷ lệ lạm phát hàng năm (phần trăm)\n
|
42 |
+
**life_expec** – Tuổi thọ trung bình khi sinh (năm)\n
|
43 |
+
**total_fer** – Tổng tỷ suất sinh (số con trung bình mỗi phụ nữ)\n
|
44 |
+
**gdpp** – GDP trên đầu người\n
|
45 |
""")
|
46 |
|
47 |
if uploaded_file is not None:
|
48 |
df = pd.read_csv(uploaded_file)
|
49 |
|
50 |
if 'df' in locals():
|
51 |
+
# Loại bỏ cột không phải số
|
52 |
categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
|
53 |
df.drop(columns=categorical_cols, inplace=True)
|
54 |
+
st.write("### Dữ liệu thô:")
|
55 |
st.write(df.head())
|
56 |
|
57 |
+
# Tiền xử lý dữ liệu
|
58 |
scaler = StandardScaler()
|
59 |
scaled_data = scaler.fit_transform(df)
|
60 |
|
61 |
+
# Chọn số lượng cụm
|
62 |
+
num_clusters = st.slider("Chọn số lượng cụm", min_value=2, max_value=10, value=3)
|
63 |
|
64 |
+
# Phân cụm bằng K-Means
|
65 |
kmeans = KMeans(n_clusters=num_clusters, random_state=42)
|
66 |
clusters = kmeans.fit_predict(scaled_data)
|
67 |
+
df['Cụm'] = clusters
|
68 |
|
69 |
+
# Giảm chiều bằng PCA để trực quan hóa
|
70 |
pca = PCA(n_components=2)
|
71 |
pca_data = pca.fit_transform(scaled_data)
|
72 |
df['PCA1'] = pca_data[:, 0]
|
73 |
df['PCA2'] = pca_data[:, 1]
|
74 |
|
75 |
+
# Vẽ biểu đồ phân cụm
|
76 |
+
st.write("### Biểu đồ Phân Cụm:")
|
77 |
fig, ax = plt.subplots()
|
78 |
+
sns.scatterplot(x='PCA1', y='PCA2', hue='Cụm', data=df, palette='viridis', ax=ax)
|
79 |
st.pyplot(fig)
|
80 |
|
81 |
+
# Vẽ biểu đồ chuỗi thời gian (nếu có)
|
82 |
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
|
83 |
if len(numeric_cols) >= 2:
|
84 |
+
selected_col = st.selectbox("Chọn cột để vẽ biểu đồ chuỗi thời gian", numeric_cols)
|
85 |
+
st.write("### Biểu đồ Chuỗi Thời Gian:")
|
86 |
fig, ax = plt.subplots()
|
87 |
+
for cluster in df['Cụm'].unique():
|
88 |
+
cluster_data = df[df['Cụm'] == cluster]
|
89 |
+
ax.plot(cluster_data.index, cluster_data[selected_col], label=f'Cụm {cluster}')
|
90 |
ax.legend()
|
91 |
st.pyplot(fig)
|
92 |
|
93 |
+
# Phân phối cụm
|
94 |
+
st.write("### Phân phối Cụm:")
|
95 |
fig, ax = plt.subplots()
|
96 |
+
sns.countplot(x='Cụm', data=df, palette='viridis', ax=ax)
|
97 |
st.pyplot(fig)
|
98 |
|
99 |
+
st.markdown("---") # Kẻ một đường ngang
|
100 |
+
st.markdown("**Cảm ơn bạn!**")
|