① trash_bag 데이터셋은 지역별 종량제 봉투 가격에 대한 정보를
포함한다. 각 용량별 가격 컬럼은 각 항의 조건을 만족하는 해당 종량제
봉투가 존재하면 가격을 값으로, 존재하지 않으면 0을 값으로 갖는다.
용도가 ’음식물쓰레기’이고 사용 대상이 ’가정용’인 2L 봉투 가격의 평균을
정수로 출력하시오. (소수점 내림)
② BMI(Body Mass Index, 체질량 지수) 는 몸무게(kg)를 키(m)의 제곱으로
나누어 계산된다.
BMI에 따른 비만도 분류는 다음과 같다.
| BMI 범위 | 비만도 분류 |
|---|---|
| 18.5 미만 | 저체중 |
| 18.5 이상 23 미만 | 정상 |
| 23이상 25 미만 | 과체중 |
| 25 이상 30 미만 | 경도비만 |
| 30 이상 | 중등도비만 |
주어진 BMI 데이터셋에서 비만도가 정상에 속하는 인원 수와 과체중에 속하는 인원 수의 차이를 정수로 출력하시오.
③ students 데이터셋은 각 학교의 학년별 총 전입학생, 총 전출학생,
전체학생 수 정보를 포함한다.
순 전입학생이 가장 많은 학교의 전체학생 수를 구하시오.
(순 전입학생 수 = 총 전입학생 수 - 총 전출학생 수)
import pandas as pd
# 데이터 로드
df = pd.read_csv(
'https://raw.githubusercontent.com/YoungjinBD/dataset/main/trash_bag.csv',
encoding='cp949'
)
# 데이터 구조와 고유값 확인
print("DataFrame 초기 확인:")## DataFrame 초기 확인:
## 시도명 시군구명 종류 처리방식 용도 ... 60L가격 75L가격 100L가격 120L가격 125L가격
## 0 강원도 강릉시 규격봉투 매립용 생활쓰레기 ... 0 1880 0 0 0
## 1 강원도 강릉시 재사용규격봉투 매립용 생활쓰레기 ... 0 0 0 0 0
## 2 강원도 고성군 규격봉투 소각용 생활쓰레기 ... 0 0 2410 0 0
## 3 강원도 고성군 규격봉투 소각용 음식물쓰레기 ... 0 0 0 0 0
## 4 강원도 고성군 특수규격마대 매립용 생활쓰레기 ... 0 0 0 0 0
##
## [5 rows x 21 columns]
## 고유값 ('용도'): ['생활쓰레기' '음식물쓰레기']
## 고유값 ('사용대상'): ['기타' '가정용' '사업장용' '영업용' '영업장용' '범용']
## 필터링된 데이터:
## 시도명 시군구명 종류 처리방식 용도 ... 60L가격 75L가격 100L가격 120L가격 125L가격
## 3 강원도 고성군 규격봉투 소각용 음식물쓰레기 ... 0 0 0 0 0
## 8 강원도 삼척시 규격봉투 매립용 음식물쓰레기 ... 0 0 0 0 0
## 9 강원도 양구군 규격봉투 매립용 음식물쓰레기 ... 0 0 0 0 0
## 12 강원도 양양군 규격봉투 기타 음식물쓰레기 ... 0 0 0 0 0
## 16 강원도 영월군 규격봉투 매립용 음식물쓰레기 ... 0 1350 0 0 0
##
## [5 rows x 21 columns]
# df_home_trash 데이터프레임에서 '2L가격'이 0이 아닌 데이터만 필터링한 뒤 '2L가격' 컬럼의 평균 계산하고 정수형태로 출력
# '2L가격'이 0이 아닌 데이터 필터링
result_df = df_home_trash.query("`2L가격` != 0")
print("필터링된 데이터 (2L가격 != 0):")## 필터링된 데이터 (2L가격 != 0):
## 시도명 시군구명 종류 처리방식 용도 ... 60L가격 75L가격 100L가격 120L가격 125L가격
## 3 강원도 고성군 규격봉투 소각용 음식물쓰레기 ... 0 0 0 0 0
## 9 강원도 양구군 규격봉투 매립용 음식물쓰레기 ... 0 0 0 0 0
## 12 강원도 양양군 규격봉투 기타 음식물쓰레기 ... 0 0 0 0 0
## 20 강원도 원주시 규격봉투 기타 음식물쓰레기 ... 0 0 0 0 0
## 33 강원도 춘천시 규격봉투 매립용 음식물쓰레기 ... 0 0 0 0 0
##
## [5 rows x 21 columns]
## '2L가격'의 평균값 (정수형): 119
import pandas as pd
# 데이터 로드
df = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/BMI.csv')
print("초기 데이터:")## 초기 데이터:
## Gender Height Weight
## 0 Male 174 96
## 1 Male 189 87
## 2 Female 185 110
## 3 Female 195 104
## 4 Male 149 61
# 키 변환 및 BMI 계산
df["Height_m"] = df["Height"] / 100
df["BMI"] = df["Weight"] / (df["Height_m"] ** 2)
print("BMI 계산 결과:")## BMI 계산 결과:
## Gender Height Weight Height_m BMI
## 0 Male 174 96 1.74 31.708284
## 1 Male 189 87 1.89 24.355421
## 2 Female 185 110 1.85 32.140248
## 3 Female 195 104 1.95 27.350427
## 4 Male 149 61 1.49 27.476240
# BMI 범주별 인원 계산
normal = df.query("18.5 <= BMI < 23").shape[0]
overweight = df.query("23 <= BMI < 25").shape[0]
print(f"정상 체중 인원: {normal}")## 정상 체중 인원: 47
## 과체중 인원: 19
# 정상 체중과 과체중 인원 차이 (절대값)
result = abs(normal - overweight)
print(f"정상 체중과 과체중 인원의 차이 (절대값): {result}")## 정상 체중과 과체중 인원의 차이 (절대값): 28
# 학교별 순 전입학생수 계산하고 순전입학생수가 제일 많은 학교의 전체 학생수 계산
import pandas as pd
# 데이터 로드
df = pd.read_csv(
'https://raw.githubusercontent.com/YoungjinBD/dataset/main/students.csv',
encoding='cp949'
)
print("초기 데이터:")## 초기 데이터:
## 학교 학년 총 전입학생 총 전출학생 전체학생 수
## 0 A 1 9 1 222
## 1 A 2 13 4 148
## 2 A 3 8 7 196
## 3 B 1 7 5 171
## 4 B 2 9 1 216
## 현재 데이터프레임의 컬럼명:
## Index(['학교', '학년', '총 전입학생', '총 전출학생', '전체학생 수'], dtype='object')
## 순 전입학생 수 추가:
## 학교 학년 총 전입학생 총 전출학생 순 전입학생 수
## 0 A 1 9 1 8
## 1 A 2 13 4 9
## 2 A 3 8 7 1
## 3 B 1 7 5 2
## 4 B 2 9 1 8
## 학교별 데이터 집계:
## 순 전입학생 수 전체학생 수
## 학교
## A 18 566
## B 13 588
## C -9 528
## D 7 548
## E 14 603
## F 1 481
## G 10 618
## H -1 602
# 최대값 조건 필터링
max_total_students = result_df.loc[
result_df['순 전입학생 수'].idxmax(),
'전체학생 수'
]
print(f"순 전입학생 수가 가장 많은 학교의 전체학생 수: {max_total_students}")## 순 전입학생 수가 가장 많은 학교의 전체학생 수: 566
used_car 데이터셋은 중고차와 관련한 정보를 가지고 있다.
| 변수 | 설명 |
|---|---|
| id | 중고차 ID 번호 |
| model | 차량 모델명 |
| year | 차량 등록 연도 |
| transmission | 변속기 종류 |
| mileage | 주행 거리 |
| fuelType | 엔진 연료 종류 |
| tax | 도로세 |
| mpg | 갤런당 마일(miles per gallon, 연비) |
| engineSize | 엔진 크기 |
| price | 가격(파운드) |
| id | price |
|---|---|
| 1 | 21350 |
| 2 | 69691 |
| 3 | 42950 |
| 4 | 31470 |
| id | model | year | transmission | mileage | fuelType | tax | mpg | engineSize |
|---|---|---|---|---|---|---|---|---|
| 1 | A1 | 2019 | Automatic | 3500 | Petrol | 145 | 40.9 | 2.0 |
| 2 | RS4 | 2020 | Semi-Auto | 2500 | Petrol | 145 | 28.8 | 2.9 |
| 3 | A8 | 2019 | Semi-Auto | 500 | Diesel | 145 | 40.4 | 3.0 |
| 4 | Q5 | 2019 | Semi-Auto | 5089 | Diesel | 150 | 38.2 | 2.0 |
주어진 학습용 데이터(used_car_y_train.csv,
used_car_X_train.csv)를 이용하여 중고차의 판매 가격을 예측하고, 이를
평가용 데이터(used_car_X_test.csv)에 적용하여 얻은 예측 결과를
다음과 같은 형식의 CSV 파일로 생성하시오.
(제출한 모델의 성능은 RMSE 평가 지표에 따라 채점)
ID,Price
1,12500
2,16500
3,11000
...
추출된 텍스트가 원본과 일치하는지 확인 후 알려주세요! 😊
import pandas as pd
# 데이터 로드
X_test = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/used_car_X_test.csv')
X_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/used_car_X_train.csv')
y_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/used_car_y_train.csv')
# 데이터 구조 확인
print("X_train 데이터프레임의 첫 5행:")## X_train 데이터프레임의 첫 5행:
## id model year transmission mileage fuelType tax mpg engineSize
## 0 1 A1 2019 Automatic 3500 Petrol 145 40.9 2.0
## 1 2 RS4 2020 Semi-Auto 2500 Petrol 145 28.8 2.9
## 2 3 A8 2019 Semi-Auto 500 Diesel 145 40.4 3.0
## 3 4 Q5 2019 Semi-Auto 5089 Diesel 150 38.2 2.0
## 4 5 A5 2020 Semi-Auto 4951 Diesel 145 51.4 2.0
# 결측치 확인
for dataset_name, dataset in zip(["X_train", "y_train", "X_test"], [X_train, y_train, X_test]):
missing_count = dataset.isnull().sum().sum()
print(f"{dataset_name}의 총 결측치 개수: {missing_count}")## X_train의 총 결측치 개수: 0
## y_train의 총 결측치 개수: 0
## X_test의 총 결측치 개수: 0
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
# 데이터 로드
X_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/used_car_X_train.csv')
X_test = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/used_car_X_test.csv')
# 숫자형 데이터와 범주형 데이터 분리
numeric_features = ['mileage', 'tax', 'mpg', 'engineSize']
categorical_features = ['model', 'transmission', 'fuelType']
X_train_num = X_train[numeric_features]
X_test_num = X_test[numeric_features]
X_train_word = X_train[categorical_features]
X_test_word = X_test[categorical_features]
# MinMaxScaler 초기화 및 스케일링
scaler = MinMaxScaler()
X_train_num_scale = scaler.fit_transform(X_train_num)
X_test_num_scale = scaler.transform(X_test_num)
# 스케일링된 데이터를 DataFrame으로 변환
df_train_num = pd.DataFrame(X_train_num_scale, columns=X_train_num.columns)
df_test_num = pd.DataFrame(X_test_num_scale, columns=X_test_num.columns)
# 원-핫 인코딩 및 타입 변환
df_train_word = pd.get_dummies(X_train_word).astype(int) # 1,0으로 코딩하기 위해 astype(int)를 넣었음
df_test_word = pd.get_dummies(X_test_word).astype(int)
# 최종 데이터 확인
print("스케일링된 숫자형 데이터 (X_train):")## 스케일링된 숫자형 데이터 (X_train):
## mileage tax mpg engineSize
## 0 0.020825 0.250000 0.127811 0.317460
## 1 0.014874 0.250000 0.056213 0.460317
## 2 0.002970 0.250000 0.124852 0.476190
## 3 0.030283 0.258621 0.111834 0.317460
## 4 0.029461 0.250000 0.189941 0.317460
## 원-핫 인코딩된 범주형 데이터 (X_train):
## model_ A1 model_ A2 ... fuelType_Hybrid fuelType_Petrol
## 0 1 0 ... 0 1
## 1 0 0 ... 0 1
## 2 0 0 ... 0 0
## 3 0 0 ... 0 0
## 4 0 0 ... 0 0
##
## [5 rows x 32 columns]
# 훈련 데이터와 테스트 데이터의 컬럼 차이 확인
train_columns = set(df_train_word.columns)
test_columns = set(df_test_word.columns)
missing_in_test = train_columns - test_columns
missing_in_train = test_columns - train_columns
print("테스트 데이터에 없는 컬럼:", missing_in_test)## 테스트 데이터에 없는 컬럼: {'model_ A2', 'model_ RS7', 'model_ S8', 'model_ S5'}
## 훈련 데이터에 없는 컬럼: set()
# 테스트 데이터에 없는 컬럼 추가
for col in missing_in_test:
df_test_word[col] = 0
# 훈련 데이터에 없는 컬럼 추가 (만약 필요할 경우)
for col in missing_in_train:
df_train_word[col] = 0
# 데이터 결합
df_train = pd.concat([df_train_num, df_train_word], axis=1)
df_test = pd.concat([df_test_num, df_test_word], axis=1)
# 결합된 데이터 확인
print("결합된 훈련 데이터:")## 결합된 훈련 데이터:
## mileage tax ... fuelType_Hybrid fuelType_Petrol
## 0 0.020825 0.250000 ... 0 1
## 1 0.014874 0.250000 ... 0 1
## 2 0.002970 0.250000 ... 0 0
## 3 0.030283 0.258621 ... 0 0
## 4 0.029461 0.250000 ... 0 0
##
## [5 rows x 36 columns]
## 결합된 테스트 데이터:
## mileage tax mpg ... model_ RS7 model_ S8 model_ S5
## 0 0.023801 0.250000 0.207101 ... 0 0 0
## 1 0.186286 0.051724 0.249112 ... 0 0 0
## 2 0.067226 0.258621 0.111834 ... 0 0 0
## 3 0.038681 0.250000 0.213609 ... 0 0 0
## 4 0.187619 0.051724 0.241420 ... 0 0 0
##
## [5 rows x 36 columns]
import xgboost as xgb
from sklearn.metrics import mean_squared_error
import numpy as np
# 데이터 확인
# print("df_train 정보:")
df_train.info()## <class 'pandas.core.frame.DataFrame'>
## RangeIndex: 7468 entries, 0 to 7467
## Data columns (total 36 columns):
## # Column Non-Null Count Dtype
## --- ------ -------------- -----
## 0 mileage 7468 non-null float64
## 1 tax 7468 non-null float64
## 2 mpg 7468 non-null float64
## 3 engineSize 7468 non-null float64
## 4 model_ A1 7468 non-null int32
## 5 model_ A2 7468 non-null int32
## 6 model_ A3 7468 non-null int32
## 7 model_ A4 7468 non-null int32
## 8 model_ A5 7468 non-null int32
## 9 model_ A6 7468 non-null int32
## 10 model_ A7 7468 non-null int32
## 11 model_ A8 7468 non-null int32
## 12 model_ Q2 7468 non-null int32
## 13 model_ Q3 7468 non-null int32
## 14 model_ Q5 7468 non-null int32
## 15 model_ Q7 7468 non-null int32
## 16 model_ Q8 7468 non-null int32
## 17 model_ R8 7468 non-null int32
## 18 model_ RS3 7468 non-null int32
## 19 model_ RS4 7468 non-null int32
## 20 model_ RS5 7468 non-null int32
## 21 model_ RS6 7468 non-null int32
## 22 model_ RS7 7468 non-null int32
## 23 model_ S3 7468 non-null int32
## 24 model_ S4 7468 non-null int32
## 25 model_ S5 7468 non-null int32
## 26 model_ S8 7468 non-null int32
## 27 model_ SQ5 7468 non-null int32
## 28 model_ SQ7 7468 non-null int32
## 29 model_ TT 7468 non-null int32
## 30 transmission_Automatic 7468 non-null int32
## 31 transmission_Manual 7468 non-null int32
## 32 transmission_Semi-Auto 7468 non-null int32
## 33 fuelType_Diesel 7468 non-null int32
## 34 fuelType_Hybrid 7468 non-null int32
## 35 fuelType_Petrol 7468 non-null int32
## dtypes: float64(4), int32(32)
## memory usage: 1.1 MB
## <class 'pandas.core.frame.DataFrame'>
## RangeIndex: 3200 entries, 0 to 3199
## Data columns (total 36 columns):
## # Column Non-Null Count Dtype
## --- ------ -------------- -----
## 0 mileage 3200 non-null float64
## 1 tax 3200 non-null float64
## 2 mpg 3200 non-null float64
## 3 engineSize 3200 non-null float64
## 4 model_ A1 3200 non-null int32
## 5 model_ A3 3200 non-null int32
## 6 model_ A4 3200 non-null int32
## 7 model_ A5 3200 non-null int32
## 8 model_ A6 3200 non-null int32
## 9 model_ A7 3200 non-null int32
## 10 model_ A8 3200 non-null int32
## 11 model_ Q2 3200 non-null int32
## 12 model_ Q3 3200 non-null int32
## 13 model_ Q5 3200 non-null int32
## 14 model_ Q7 3200 non-null int32
## 15 model_ Q8 3200 non-null int32
## 16 model_ R8 3200 non-null int32
## 17 model_ RS3 3200 non-null int32
## 18 model_ RS4 3200 non-null int32
## 19 model_ RS5 3200 non-null int32
## 20 model_ RS6 3200 non-null int32
## 21 model_ S3 3200 non-null int32
## 22 model_ S4 3200 non-null int32
## 23 model_ SQ5 3200 non-null int32
## 24 model_ SQ7 3200 non-null int32
## 25 model_ TT 3200 non-null int32
## 26 transmission_Automatic 3200 non-null int32
## 27 transmission_Manual 3200 non-null int32
## 28 transmission_Semi-Auto 3200 non-null int32
## 29 fuelType_Diesel 3200 non-null int32
## 30 fuelType_Hybrid 3200 non-null int32
## 31 fuelType_Petrol 3200 non-null int32
## 32 model_ A2 3200 non-null int64
## 33 model_ RS7 3200 non-null int64
## 34 model_ S8 3200 non-null int64
## 35 model_ S5 3200 non-null int64
## dtypes: float64(4), int32(28), int64(4)
## memory usage: 550.1 KB
XGBRegressor(base_score=None, booster=None, callbacks=None,
colsample_bylevel=None, colsample_bynode=None,
colsample_bytree=None, device=None, early_stopping_rounds=None,
enable_categorical=False, eval_metric=None, feature_types=None,
gamma=None, grow_policy=None, importance_type=None,
interaction_constraints=None, learning_rate=None, max_bin=None,
max_cat_threshold=None, max_cat_to_onehot=None,
max_delta_step=None, max_depth=None, max_leaves=None,
min_child_weight=None, missing=nan, monotone_constraints=None,
multi_strategy=None, n_estimators=None, n_jobs=None,
num_parallel_tree=None, random_state=77, ...)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. XGBRegressor(base_score=None, booster=None, callbacks=None,
colsample_bylevel=None, colsample_bynode=None,
colsample_bytree=None, device=None, early_stopping_rounds=None,
enable_categorical=False, eval_metric=None, feature_types=None,
gamma=None, grow_policy=None, importance_type=None,
interaction_constraints=None, learning_rate=None, max_bin=None,
max_cat_threshold=None, max_cat_to_onehot=None,
max_delta_step=None, max_depth=None, max_leaves=None,
min_child_weight=None, missing=nan, monotone_constraints=None,
multi_strategy=None, n_estimators=None, n_jobs=None,
num_parallel_tree=None, random_state=77, ...)# 검증 데이터로 성능 평가
y_pred = model.predict(df_train)
rmse = np.sqrt(mean_squared_error(y_train["price"], y_pred))
print(f"\n검증 데이터 RMSE: {rmse:.2f}")##
## 검증 데이터 RMSE: 1693.07
missing_in_test = set(df_train.columns) - set(df_test.columns)
missing_in_train = set(df_test.columns) - set(df_train.columns)
print("테스트 데이터에 없는 컬럼:", missing_in_test)## 테스트 데이터에 없는 컬럼: set()
## 훈련 데이터에 없는 컬럼: set()
## df_train 컬럼: Index(['mileage', 'tax', 'mpg', 'engineSize', 'model_ A1', 'model_ A2',
## 'model_ A3', 'model_ A4', 'model_ A5', 'model_ A6', 'model_ A7',
## 'model_ A8', 'model_ Q2', 'model_ Q3', 'model_ Q5', 'model_ Q7',
## 'model_ Q8', 'model_ R8', 'model_ RS3', 'model_ RS4', 'model_ RS5',
## 'model_ RS6', 'model_ RS7', 'model_ S3', 'model_ S4', 'model_ S5',
## 'model_ S8', 'model_ SQ5', 'model_ SQ7', 'model_ TT',
## 'transmission_Automatic', 'transmission_Manual',
## 'transmission_Semi-Auto', 'fuelType_Diesel', 'fuelType_Hybrid',
## 'fuelType_Petrol'],
## dtype='object')
## df_test 컬럼: Index(['mileage', 'tax', 'mpg', 'engineSize', 'model_ A1', 'model_ A3',
## 'model_ A4', 'model_ A5', 'model_ A6', 'model_ A7', 'model_ A8',
## 'model_ Q2', 'model_ Q3', 'model_ Q5', 'model_ Q7', 'model_ Q8',
## 'model_ R8', 'model_ RS3', 'model_ RS4', 'model_ RS5', 'model_ RS6',
## 'model_ S3', 'model_ S4', 'model_ SQ5', 'model_ SQ7', 'model_ TT',
## 'transmission_Automatic', 'transmission_Manual',
## 'transmission_Semi-Auto', 'fuelType_Diesel', 'fuelType_Hybrid',
## 'fuelType_Petrol', 'model_ A2', 'model_ RS7', 'model_ S8', 'model_ S5'],
## dtype='object')
df_test = df_test[df_train.columns] # test의 컬럼 순서를 train과 동일하게 변경
# 예측 수행
y_pred1 = model.predict(df_test)
df_result = pd.DataFrame({'price': y_pred1})
# 결과 확인
print("예측 결과 데이터프레임:")## 예측 결과 데이터프레임:
## price
## 0 29922.884766
## 1 17874.656250
## 2 34470.707031
## 3 15347.687500
## 4 15160.128906
## 결과가 result.csv 파일에 저장되었습니다.
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import numpy as np
# 예측값과 실제값
y_pred = model.predict(df_train) # 검증 데이터 예측값
y_actual = y_train["price"] # 검증 데이터 실제값
# 평가 지표 계산
mse = mean_squared_error(y_actual, y_pred)
rmse = np.sqrt(mse)
mae = mean_absolute_error(y_actual, y_pred)
r2 = r2_score(y_actual, y_pred)
# 결과 출력
print(f"Mean Squared Error (MSE): {mse:.2f}")## Mean Squared Error (MSE): 2866489.89
## Root Mean Squared Error (RMSE): 1693.07
## Mean Absolute Error (MAE): 1240.98
## R-squared (R²): 0.98