제 1 유형


데이터셋 : https://raw.githubusercontent.com/YoungjinBD/dataset/main/airquality.csv

주어지는 데이터는 153일 동안 공기의 질을 측정한 데이터셋이다.

컬럼 설명
Ozone 오존 농도
Solar.R 태양 복사 강도
Wind 평균 풍속
Temp 최대 온도
Month
Day
  1. airquality 데이터에 대해서 결측치가 가장 많은 변수를 찾아서 해당 결측치를 0으로 대치하고, 결측치를 제외한 평균과 0으로 대치한 후의 평균과의 차이를 구하시오.

  2. Wind 변수에 대해서 Min-Max 정규화를 수행한 후 평균값과 Z 정규화를 수행한 후 평균 값의 차이를 구하시오.

  3. 월별(5월~9월) 평균 기온을 구하시오.

# 구글 코랩 환경을 기준으로 하고 있습니다.
import pandas as pd
import numpy as np

# csv 파일이 위치한 디렉토리 입력
df = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/airquality.csv')
df
##      Ozone  Solar.R  Wind  Temp  Month  Day
## 0     41.0    190.0   7.4    67      5    1
## 1     36.0    118.0   8.0    72      5    2
## 2     12.0    149.0  12.6    74      5    3
## 3     18.0    313.0  11.5    62      5    4
## 4      NaN      NaN  14.3    56      5    5
## ..     ...      ...   ...   ...    ...  ...
## 148   30.0    193.0   6.9    70      9   26
## 149    NaN    145.0  13.2    77      9   27
## 150   14.0    191.0  14.3    75      9   28
## 151   18.0    131.0   8.0    76      9   29
## 152   20.0    223.0  11.5    68      9   30
## 
## [153 rows x 6 columns]
df.info()
## <class 'pandas.core.frame.DataFrame'>
## RangeIndex: 153 entries, 0 to 152
## Data columns (total 6 columns):
##  #   Column   Non-Null Count  Dtype  
## ---  ------   --------------  -----  
##  0   Ozone    116 non-null    float64
##  1   Solar.R  146 non-null    float64
##  2   Wind     153 non-null    float64
##  3   Temp     153 non-null    int64  
##  4   Month    153 non-null    int64  
##  5   Day      153 non-null    int64  
## dtypes: float64(3), int64(3)
## memory usage: 7.3 KB
# Ozone 컬럼의 결측치를 0으로 대체
# 대체 이전과 이후의 평균을 출력

# Ozone 컬럼의 결측치 개수 확인 및 평균 계산
print("Ozone 결측치 개수 (대체 이전):", df["Ozone"].isnull().sum())
## Ozone 결측치 개수 (대체 이전): 37
Ozone_mean_before = df["Ozone"].mean()  # 대체 이전 Ozone 컬럼의 평균
print("Ozone 평균 (대체 이전):", Ozone_mean_before)
## Ozone 평균 (대체 이전): 42.12931034482759
# Ozone 컬럼의 결측치를 0으로 대체
df["Ozone"] = df["Ozone"].fillna(0)

# Ozone 컬럼의 결측치 개수 확인 및 평균 계산 (대체 이후)
print("Ozone 결측치 개수 (대체 이후):", df["Ozone"].isnull().sum())
## Ozone 결측치 개수 (대체 이후): 0
Ozone_mean_after = df["Ozone"].mean()  # 대체 이후 Ozone 컬럼의 평균
print("Ozone 평균 (대체 이후):", Ozone_mean_after)
## Ozone 평균 (대체 이후): 31.941176470588236
print("\nOzone 평균 차이(대체이전-이후)",Ozone_mean_before-Ozone_mean_after)
## 
## Ozone 평균 차이(대체이전-이후) 10.188133874239352
# Wind 필드 Min-Max 표준화, Z 표준화 변환뒤 컬럼 추가
# 소수점 2자리까지 표시

# Min-Max 표준화
df["min_max"] = ((df["Wind"] - df["Wind"].min()) / (df["Wind"].max() - df["Wind"].min())).round(2)

# Z-표준화
df["z"] = ((df["Wind"] - df["Wind"].mean()) / df["Wind"].std()).round(2)


df
##      Ozone  Solar.R  Wind  Temp  Month  Day  min_max     z
## 0     41.0    190.0   7.4    67      5    1     0.30 -0.73
## 1     36.0    118.0   8.0    72      5    2     0.33 -0.56
## 2     12.0    149.0  12.6    74      5    3     0.57  0.75
## 3     18.0    313.0  11.5    62      5    4     0.52  0.44
## 4      0.0      NaN  14.3    56      5    5     0.66  1.23
## ..     ...      ...   ...   ...    ...  ...      ...   ...
## 148   30.0    193.0   6.9    70      9   26     0.27 -0.87
## 149    0.0    145.0  13.2    77      9   27     0.61  0.92
## 150   14.0    191.0  14.3    75      9   28     0.66  1.23
## 151   18.0    131.0   8.0    76      9   29     0.33 -0.56
## 152   20.0    223.0  11.5    68      9   30     0.52  0.44
## 
## [153 rows x 8 columns]
# Wind 필드 Min-Max 표준화, Z 표준화 변환뒤 컬럼 추가
# 소수점 2자리까지 표시

from sklearn.preprocessing import MinMaxScaler, StandardScaler, scale

# Min-Max 표준화
min_max_scaler = MinMaxScaler()
df["min_max"] = min_max_scaler.fit_transform(df[["Wind"]]).round(2)

# Z-표준화 (Z-score)
z_scaler = StandardScaler()
df["z"] = z_scaler.fit_transform(df[["Wind"]]).round(2)
df["z1"] = scale(df["Wind"]).round(2)

df
##      Ozone  Solar.R  Wind  Temp  Month  Day  min_max     z    z1
## 0     41.0    190.0   7.4    67      5    1     0.30 -0.73 -0.73
## 1     36.0    118.0   8.0    72      5    2     0.33 -0.56 -0.56
## 2     12.0    149.0  12.6    74      5    3     0.57  0.75  0.75
## 3     18.0    313.0  11.5    62      5    4     0.52  0.44  0.44
## 4      0.0      NaN  14.3    56      5    5     0.66  1.24  1.24
## ..     ...      ...   ...   ...    ...  ...      ...   ...   ...
## 148   30.0    193.0   6.9    70      9   26     0.27 -0.87 -0.87
## 149    0.0    145.0  13.2    77      9   27     0.61  0.92  0.92
## 150   14.0    191.0  14.3    75      9   28     0.66  1.24  1.24
## 151   18.0    131.0   8.0    76      9   29     0.33 -0.56 -0.56
## 152   20.0    223.0  11.5    68      9   30     0.52  0.44  0.44
## 
## [153 rows x 9 columns]
df.describe()
##             Ozone     Solar.R        Wind  ...     min_max           z          z1
## count  153.000000  146.000000  153.000000  ...  153.000000  153.000000  153.000000
## mean    31.941176  185.931507    9.957516  ...    0.433333   -0.000065   -0.000065
## std     33.924497   90.058422    3.523001  ...    0.185696    1.003679    1.003679
## min      0.000000    7.000000    1.700000  ...    0.000000   -2.350000   -2.350000
## 25%      4.000000  115.750000    7.400000  ...    0.300000   -0.730000   -0.730000
## 50%     21.000000  205.000000    9.700000  ...    0.420000   -0.070000   -0.070000
## 75%     46.000000  258.750000   11.500000  ...    0.520000    0.440000    0.440000
## max    168.000000  334.000000   20.700000  ...    1.000000    3.060000    3.060000
## 
## [8 rows x 9 columns]
# 월별 평균기온
print(df.groupby("Month")['Temp'].mean())
## Month
## 5    65.548387
## 6    79.100000
## 7    83.903226
## 8    83.967742
## 9    76.900000
## Name: Temp, dtype: float64

제 2 유형


데이터셋 : https://raw.githubusercontent.com/YoungjinBD/dataset/main/Bank_Personal_Loan_Modeling.csv

은행 고객 5,000명에 대한 데이터로 인구통계정보(연령, 소득 등), 고객과의 관계(담보, 증권계좌 등), 개인대출 등의 금융정보를 포함한다.

은행에서 수집한 고객 5,000명의 금융정보에 따른 대출여부가 들어있는 참조데이터를 이용하여 대출여부를 분류하는 가장 최적의 이웃의 크기값(k)을 구하고, 이때 분류정확도를 산출하시오.

(단, 참조데이터는 7:3의 비율로 트레이닝 데이터와 테스트 데이터로 구분하고, 트레이닝 데이터와 테스트 데이터의 대출여부(y)의 비율도 유지한다. 또한 normalizer를 사용하여 스케일링을 진행한다.)


# 구글 코랩 환경을 기준으로 하고 있습니다.
import numpy as np
import pandas as pd
import sklearn

ploan = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/Bank_Personal_Loan_Modeling.csv')
# 구글 코랩 환경을 기준으로 하고 있습니다.
import numpy as np
import pandas as pd
import sklearn

ploan = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/Bank_Personal_Loan_Modeling.csv')

ploan.shape     # 데이터 차원 확인
## (5000, 14)
ploan.head(10)  # 데이터 예시 확인
##    ID  Age  Experience  ...  CD Account  Online  CreditCard
## 0   1   25           1  ...           0       0           0
## 1   2   45          19  ...           0       0           0
## 2   3   39          15  ...           0       0           0
## 3   4   35           9  ...           0       0           0
## 4   5   35           8  ...           0       0           1
## 5   6   37          13  ...           0       1           0
## 6   7   53          27  ...           0       1           0
## 7   8   50          24  ...           0       0           1
## 8   9   35          10  ...           0       1           0
## 9  10   34           9  ...           0       0           0
## 
## [10 rows x 14 columns]
ploan.info()
## <class 'pandas.core.frame.DataFrame'>
## RangeIndex: 5000 entries, 0 to 4999
## Data columns (total 14 columns):
##  #   Column              Non-Null Count  Dtype  
## ---  ------              --------------  -----  
##  0   ID                  5000 non-null   int64  
##  1   Age                 5000 non-null   int64  
##  2   Experience          5000 non-null   int64  
##  3   Income              5000 non-null   int64  
##  4   ZIP Code            5000 non-null   int64  
##  5   Family              5000 non-null   int64  
##  6   CCAvg               5000 non-null   float64
##  7   Education           5000 non-null   int64  
##  8   Mortgage            5000 non-null   int64  
##  9   Personal Loan       5000 non-null   int64  
##  10  Securities Account  5000 non-null   int64  
##  11  CD Account          5000 non-null   int64  
##  12  Online              5000 non-null   int64  
##  13  CreditCard          5000 non-null   int64  
## dtypes: float64(1), int64(13)
## memory usage: 547.0 KB
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Normalizer

# 1. 불필요한 변수 제거 및 결측치 제거
ploan_processed = ploan.dropna().drop(['ID', 'ZIP Code'], axis=1)

# 2. 독립변수(X)와 종속변수(y) 분리
X = ploan_processed.drop("Personal Loan", axis=1)
y = ploan_processed["Personal Loan"]  # 타겟변수: 0 또는 1

# 3. 학습 데이터와 테스트 데이터 분리 (7:3 비율, 계층 샘플링 사용)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, stratify=y, train_size=0.7, random_state=1234
)

# 4. 데이터 정규화
normalizer = Normalizer()
X_train = normalizer.fit_transform(X_train)
X_test = normalizer.transform(X_test)

# 5. 결과 확인
print(f"X_train shape: {X_train.shape}, X_test shape: {X_test.shape}")
## X_train shape: (3500, 11), X_test shape: (1500, 11)
print(f"y_train shape: {y_train.shape}, y_test shape: {y_test.shape}")
## y_train shape: (3500,), y_test shape: (1500,)
# K 값(이웃 수)을 1부터 24까지 변경하며 KNN 모델을 반복적으로 학습.
# 각 K 값에 대해 훈련 데이터와 테스트 데이터의 정확도를 계산.
# 훈련 데이터와 테스트 데이터의 정확도를 각각 리스트에 저장.
# 훈련 데이터와 테스트 데이터의 정확도를 최종 출력.

from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.neighbors import KNeighborsClassifier

training_accuracy = []
test_accuracy = []

# 1 에서 25 까지 n_neighbors를 적용
neighbors_settings = range(1, 25)

# KNeighborsClassifier() 함수에 K개수를 입력하여 모델을 만들고 트레이닝 데이터와 테스트 데이터를 적용
for n_neighbors in neighbors_settings:
    # 모델 생성
    clf = KNeighborsClassifier(n_neighbors=n_neighbors)
    clf.fit(X_train, y_train)
    # 훈련 세트 정확도 저장
    training_accuracy.append(clf.score(X_train, y_train))
    # 일반화 정확도 저장
    test_accuracy.append(clf.score(X_test, y_test))
KNeighborsClassifier(n_neighbors=24)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
    
training_accuracy
## [1.0, 0.9542857142857143, 0.964, 0.9394285714285714, 0.9471428571428572, 0.9322857142857143, 0.938, 0.9262857142857143, 0.9331428571428572, 0.9231428571428572, 0.9257142857142857, 0.9205714285714286, 0.9237142857142857, 0.9177142857142857, 0.9217142857142857, 0.9171428571428571, 0.9182857142857143, 0.9168571428571428, 0.9191428571428572, 0.9194285714285715, 0.9197142857142857, 0.9182857142857143, 0.9194285714285715, 0.9162857142857143]
test_accuracy
## [0.9213333333333333, 0.9213333333333333, 0.9246666666666666, 0.92, 0.926, 0.916, 0.9166666666666666, 0.9173333333333333, 0.9166666666666666, 0.918, 0.916, 0.914, 0.914, 0.91, 0.914, 0.9093333333333333, 0.91, 0.908, 0.908, 0.9093333333333333, 0.9093333333333333, 0.9073333333333333, 0.9073333333333333, 0.9086666666666666]

제 3 유형


데이터셋 : https://raw.githubusercontent.com/YoungjinBD/dataset/main/airquality.csv

측정한 온도(Temp)의 평균값이 평균온도인 77과 일치하는지 t-검정을 이용하여 확인하시오.

  1. 표본평균 X̄를 소수점 둘째자리까지 반올림하여 구하시오.

  2. 가설검정을 위한 검정통계량을 소수점 둘째자리까지 반올림하여 구하시오.

  3. 통계량에 대한 p-value 값을 소수점 넷째자리까지 반올림하여 구하고, 유의수준 0.05 내에서 결과를 논의하시오. (채택과 기각 중 선택)


import pandas as pd
import scipy.stats as stats

# csv 파일이 위치 입력
df = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/airquality.csv')
X = df['Temp'].mean()
print(round(X, 2))
## 77.88
  • 단일 표본 t-검정(One-sample t-test)을 사용하여, df['Temp'] 데이터의 평균이 77과 통계적으로 유의미하게 다른지 확인합니다.

t_score, p_value = stats.ttest_1samp(df['Temp'], 77)
print(round(t_score, 2))
## 1.15
print(round(p_value, 4))
## 0.2507
pv= round(p_value, 4)
print(pv)
## 0.2507
if pv < 0.05:
    print('귀무가설 기각')
else:
    print('귀무가설 채택')
## 귀무가설 채택