JUNGU commited on
Commit
68fece7
·
verified ·
1 Parent(s): 1ed753b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +94 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,96 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ from scipy.stats import norm, skew
7
+ import platform
8
+
9
+ # 한글 폰트 설정 (Windows, Mac, Linux 환경에 맞게 자동 설정)
10
+ if platform.system() == 'Windows':
11
+ plt.rc('font', family='Malgun Gothic')
12
+ elif platform.system() == 'Darwin': # Mac
13
+ plt.rc('font', family='AppleGothic')
14
+ else: # Linux
15
+ # 나눔고딕 폰트가 설치되어 있어야 합니다.
16
+ # sudo apt-get install fonts-nanum*
17
+ plt.rc('font', family='NanumGothic')
18
+
19
+ plt.rcParams['axes.unicode_minus'] = False # 마이너스 폰트 깨짐 방지
20
+
21
+ def main():
22
+ """
23
+ 스트림릿을 이용한 학생 점수 분포 분석 애플리케이션
24
+ """
25
+ st.title("학생 점수 분포 분석 도구 📊")
26
+ st.write("CSV 파일을 업로드하여 학생들의 점수 분포를 확인하고, 정규분포와의 차이 및 왜도(skewness)를 분석합니다.")
27
+ st.write("---")
28
+
29
+ # 파일 업로드 위젯
30
+ uploaded_file = st.file_uploader("점수 데이터가 포함된 CSV 파일을 업로드하세요.", type="csv")
31
+
32
+ if uploaded_file is not None:
33
+ try:
34
+ # utf-8-sig 인코딩으로 CSV 파일 읽기
35
+ df = pd.read_csv(uploaded_file, encoding='utf-8-sig')
36
+
37
+ st.subheader("업로드된 데이터 미리보기")
38
+ st.dataframe(df.head())
39
+
40
+ # 분석할 점수 열 선택
41
+ score_column = st.selectbox("분석할 점수 열(column)을 선택하세요:", df.columns)
42
+
43
+ if score_column:
44
+ # 선택된 열의 데이터 추출 (결측치 제거)
45
+ scores = df[score_column].dropna()
46
+
47
+ if pd.api.types.is_numeric_dtype(scores):
48
+ st.subheader(f"'{score_column}' 점수 분포 분석 결과")
49
+
50
+ # 1. 기술 통계량 표시
51
+ st.write("#### 📈 기술 통계량")
52
+ st.table(scores.describe())
53
+
54
+ # 2. 분포 시각화 및 정규분포 비교
55
+ st.write("#### 🎨 점수 분포 시각화")
56
+ fig, ax = plt.subplots(figsize=(10, 6))
57
+
58
+ # 히스토그램 및 KDE 플롯
59
+ sns.histplot(scores, kde=True, stat='density', label='학생 점수 분포', ax=ax)
60
+
61
+ # 정규분포 곡선 추가
62
+ mu, std = norm.fit(scores)
63
+ xmin, xmax = plt.xlim()
64
+ x = np.linspace(xmin, xmax, 100)
65
+ p = norm.pdf(x, mu, std)
66
+ ax.plot(x, p, 'k', linewidth=2, label='정규분포 곡선')
67
+
68
+ title = f"'{score_column}' 점수 분포 (평균: {mu:.2f}, 표준편차: {std:.2f})"
69
+ ax.set_title(title)
70
+ ax.set_xlabel('점수')
71
+ ax.set_ylabel('밀도')
72
+ ax.legend()
73
+ st.pyplot(fig)
74
+
75
+ # 3. 왜도(Skewness) 계산 및 해석
76
+ st.write("#### 📐 왜도 (Skewness) 분석")
77
+ skewness = skew(scores)
78
+ st.metric(label="왜도 (Skewness)", value=f"{skewness:.4f}")
79
+
80
+ if skewness > 0.5:
81
+ st.info("꼬리가 오른쪽으로 긴 분포 (Positive Skew): 대부분의 학생들이 평균보다 낮은 점수에 몰려있고, 일부 학생들이 매우 높은 점수를 받았습니다.")
82
+ elif skewness < -0.5:
83
+ st.info("꼬리가 왼쪽으로 긴 분포 (Negative Skew): 대부분의 학생들이 평균보다 높은 점수에 몰려있고, 일부 학생들이 매우 낮은 점수를 받았습니다.")
84
+ else:
85
+ st.info("대칭에 가까운 분포: 점수가 평균을 중심으로 비교적 고르게 분포되어 있습니다.")
86
+
87
+ else:
88
+ st.error(f"오류: 선택하신 '{score_column}' 열은 숫자 데이터가 아닙니다. 숫자 데이터로 구성된 열을 선택해주세요.")
89
+
90
+ except Exception as e:
91
+ st.error(f"파일을 읽는 도중 오류가 발생했습니다: {e}")
92
+ st.warning("CSV 파일이 'utf-8-sig' 또는 'utf-8' 인코딩 형식인지 확인해주세요.")
93
+
94
 
95
+ if __name__ == '__main__':
96
+ main()