hoangkha1810 commited on
Commit
d880f04
·
verified ·
1 Parent(s): 87b9b04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -46
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
- # App Title
12
- st.title("Unsupervised Data Clustering App")
13
 
14
- # About App
15
- with st.expander("About this App"):
16
  st.write(
17
- "This app allows you to upload any type of unlabeled dataset "
18
- "and automatically clusters the data using K-means clustering. "
19
- "It visualizes the clusters using PCA and provides time series and cluster distribution plots "
20
- "to help you identify patterns and groupings within your data."
21
  )
22
 
23
- # File uploader
24
- uploaded_file = st.file_uploader("Upload Custom CSV file", type=["csv"])
25
 
26
- # # Example Demo Dataset
27
- if st.button("Test With An Example Dataset"):
28
  dataset = load_dataset('kheejay88/country_data', split='train')
29
  df = pd.DataFrame(dataset)
30
- st.success("Loaded example dataset from Hugging Face.")
31
 
32
- with st.expander("Dataset Columns"):
 
33
  st.write("""
34
- **country** – Name of the country\n
35
- **child_mort** – Death of children under 5 years of age per 1000 live births\n
36
- **exports** – Exports of goods and services per capita (as a percentage of GDP)\n
37
- **health** – Total health spending per capita (as a percentage of GDP)\n
38
- **imports** – Imports of goods and services per capita (as a percentage of GDP)\n
39
- **income** – Net income per person\n
40
- **inflation** – Annual inflation rate (percentage)\n
41
- **life_expec** – Average life expectancy at birth (in years)\n
42
- **total_fer** – Total fertility rate (average number of children per woman)\n
43
- **gdpp** – GDP per capita\n
44
  """)
45
 
46
  if uploaded_file is not None:
47
  df = pd.read_csv(uploaded_file)
48
 
49
  if 'df' in locals():
50
- # Drop non-numeric columns
51
  categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
52
  df.drop(columns=categorical_cols, inplace=True)
53
- st.write("### Raw Data:")
54
  st.write(df.head())
55
 
56
- # Preprocessing
57
  scaler = StandardScaler()
58
  scaled_data = scaler.fit_transform(df)
59
 
60
- # User input for clusters
61
- num_clusters = st.slider("Select number of clusters", min_value=2, max_value=10, value=3)
62
 
63
- # K-Means Clustering
64
  kmeans = KMeans(n_clusters=num_clusters, random_state=42)
65
  clusters = kmeans.fit_predict(scaled_data)
66
- df['Cluster'] = clusters
67
 
68
- # PCA for visualization
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
- # Plot Clusters
75
- st.write("### Cluster Visualization:")
76
  fig, ax = plt.subplots()
77
- sns.scatterplot(x='PCA1', y='PCA2', hue='Cluster', data=df, palette='viridis', ax=ax)
78
  st.pyplot(fig)
79
 
80
- # Time Series Plot (if available)
81
  numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
82
  if len(numeric_cols) >= 2:
83
- selected_col = st.selectbox("Select column for time series visualization", numeric_cols)
84
- st.write("### Time Series Plot:")
85
  fig, ax = plt.subplots()
86
- for cluster in df['Cluster'].unique():
87
- cluster_data = df[df['Cluster'] == cluster]
88
- ax.plot(cluster_data.index, cluster_data[selected_col], label=f'Cluster {cluster}')
89
  ax.legend()
90
  st.pyplot(fig)
91
 
92
- # Cluster distribution
93
- st.write("### Cluster Distribution:")
94
  fig, ax = plt.subplots()
95
- sns.countplot(x='Cluster', data=df, palette='viridis', ax=ax)
96
  st.pyplot(fig)
97
 
98
- st.markdown("---") # Adds a horizontal line
99
- st.markdown("**Thanks!**")
 
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
+ " tự động phân cụm dữ liệu bằng thuật toán K-means. "
19
+ " sẽ trực quan hóa các cụm bằng phương pháp PCA 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 hình 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 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 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 )
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!**")