-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial4.py
More file actions
100 lines (79 loc) · 2.86 KB
/
tutorial4.py
File metadata and controls
100 lines (79 loc) · 2.86 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import pandas as pd
def read_attr(attr_path: str) -> list[str]:
with open(attr_path, 'r', encoding='utf-8') as f:
return f.read().splitlines()
def load_data(data_path: str, attr: list[str]) -> pd.DataFrame:
return pd.read_csv(data_path, header=None, names=attr, encoding='utf-8')
def split_label_inplace(df: pd.DataFrame) -> None:
df['label'] = df['name'].copy()
df.drop(columns=['name'], inplace=True)
def minmax_scale_inplace(
df: pd.DataFrame, exclude_cols: tuple[str, ...] = ('label',)
) -> list[str]:
num_cols = df.select_dtypes(include='number').columns.tolist()
for col in exclude_cols:
if col in num_cols:
num_cols.remove(col)
if not num_cols:
return []
mn = df[num_cols].min()
mx = df[num_cols].max()
rng = mx - mn
const_cols = rng[rng == 0].index.tolist()
var_cols = rng[rng != 0].index.tolist()
if var_cols:
df[var_cols] = (df[var_cols] - mn[var_cols]).div(rng[var_cols])
if const_cols:
df[const_cols] = 0.0
return num_cols
def print_summary(
df: pd.DataFrame, orig_shape: tuple[int, int], num_cols: list[str]
) -> None:
print(f"[1] 원본 DataFrame 모양: {orig_shape}")
print("[2] 라벨 분포:")
print(df['label'].value_counts(dropna=False))
if num_cols:
desc = df[num_cols].describe()
minmax = desc.loc[['min', 'max']].round(6).to_dict()
print("[3] 스케일 결과 상/하한 요약:")
print(minmax)
else:
print("[3] 스케일 대상 수치 컬럼이 없습니다.")
def main(attr_path: str = 'a_attr', data_path: str = 'a') -> None:
# 1. 데이터 적재
try:
attr = read_attr(attr_path)
except FileNotFoundError:
print(f"[오류] 파일 열기 실패: {attr_path}")
return
except UnicodeDecodeError as e:
print(f"[오류] 디코딩 오류({attr_path}): {e}")
return
except OSError as e:
print(f"[오류] 파일 열기 실패({attr_path}): {e}")
return
try:
df = load_data(data_path, attr)
except FileNotFoundError:
print(f"[오류] 파일 열기 실패: {data_path}")
return
except UnicodeDecodeError as e:
print(f"[오류] 디코딩 오류({data_path}): {e}")
return
except OSError as e:
print(f"[오류] 파일 열기 실패({data_path}): {e}")
return
except Exception as e:
print(f"[오류] 파싱/스케일링 단계 기타 오류(읽기): {e}")
return
# 2, 3. 라벨 분리 + 스케일링
try:
orig_shape = df.shape
split_label_inplace(df)
num_cols = minmax_scale_inplace(df, exclude_cols=('label',))
print_summary(df, orig_shape, num_cols)
except Exception as e:
print(f"[오류] 파싱/스케일링 단계 기타 오류: {e}")
return
if __name__ == "__main__":
main()