① 아래의 리스트에 대해 아래 과정을 차례로 수행한 최종 결과값을 출력하시오.
② 주어진 facebook 데이터셋은 페이스북 라이브에 대한 사용자 반응을 집계한 것이다. 이 중 love 반응(num_loves)와 wow 반응(num_wows)을 매우 긍정적인 반응이라고 정의할 때, 전체 반응 수(num_reaction) 중 매우 긍정적인 반응 수가 차지하는 비율을 계산하시오. 그리고 그 비율이 0.4 보다 크고 0.5보다 작으면, 유형이 비디오에 해당하는 경우를 정수로 출력하시오.
③ netflix 데이터셋은 넷플릭스에 등록된 컨텐츠의 메타 데이터이다. 2018년 01월 넷플릭스에 등록된 컨텐츠 중에서 ’United Kingdom’이 단독 제작한 컨텐츠의 수를 정수로 출력하시오.
import numpy as np
lst = [10, 11, 11.2, 13, 15.5, 18, 19.8, 20, 31, 33, 39.5, 42]
# 제1사분위수
q1 = np.percentile(lst, 25)
# 제3사분위수
q3 = np.percentile(lst, 75)
print(q1)## 12.55
## 31.5
## 18.95
## 18
Q1 (제1사분위수): 12.55
Q3 (제3사분위수): 31.5
IQR (사분위수 범위): Q3−Q1 = 18.95
출력 결과 (정수): 18
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/facebook.csv')
print(df.head())## status_id status_type ... num_sads num_angrys
## 0 246675545449582_1649696485147474 video ... 1 0
## 1 246675545449582_1649426988507757 photo ... 0 0
## 2 246675545449582_1648730588577397 video ... 0 0
## 3 246675545449582_1648576705259452 photo ... 0 0
## 4 246675545449582_1645700502213739 photo ... 0 0
##
## [5 rows x 11 columns]
## count 6929.000000
## mean 0.049604
## std 0.101727
## min 0.000000
## 25% 0.000000
## 50% 0.000000
## 75% 0.040000
## max 1.000000
## Name: positive, dtype: float64
result_df = df[(df['positive'] >0.4) & (df['positive']<0.5) & (df['status_type']=='video')]
result = len(result_df)
print(result)## 90
데이터 구조:
num_reactions)를
기준으로 긍정적 반응 비율(positive)을 계산.positive 통계량:
평균: 약 0.049604
최대값: 1.0
필터링 결과:
positive 값이 0.4 ~ 0.5 범위이고, status_type이 ’video’인
데이터는 총 90개입니다.# Netflix 데이터를 로드하여 데이터 구조 확인 및 특정 열 데이터 추출을 수행
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/netflix.csv')
print(df.head())## show_id ... description
## 0 s1 ... As her father nears the end of his life, filmm...
## 1 s2 ... After crossing paths at a party, a Cape Town t...
## 2 s3 ... To protect his family from a powerful drug lor...
## 3 s4 ... Feuds, flirtations and toilet talk go down amo...
## 4 s5 ... In a city of coaching centers known to train I...
##
## [5 rows x 12 columns]
## 0 September 25, 2021
## 1 September 24, 2021
## 2 September 24, 2021
## 3 September 24, 2021
## 4 September 24, 2021
## ...
## 8802 November 20, 2019
## 8803 July 1, 2019
## 8804 November 1, 2019
## 8805 January 11, 2020
## 8806 March 2, 2019
## Name: date_added, Length: 8807, dtype: object
# Netflix 데이터에서 특정 조건(추가 날짜에 "January"와 "2018"을 포함하는 데이터)을 만족하는 콘텐츠를 필터링하고, 해당 결과를 출력
result_df = df[df['date_added'].str.contains('January')&df['date_added'].str.contains('2018')]
print(result_df.head())## show_id ... description
## 5055 s5056 ... A filmmaker and his musician girlfriend attemp...
## 5056 s5057 ... Months after his classic TV sitcom ends, the l...
## 5057 s5058 ... A dark web of secrets and lies emerges when a ...
## 5058 s5059 ... In this musical comedy, two rebellious teen gi...
## 5059 s5060 ... In a brief life full of triumph and failure, "...
##
## [5 rows x 12 columns]
# Netflix 데이터에서 특정 조건에 해당하는 콘텐츠를 필터링하고, "United Kingdom"에서 제작된 콘텐츠의 개수를 계산하는 작업을 수행
result_df_UK = result_df[result_df['country'] =='United Kingdom']
result = len(result_df_UK)
print(result)## 6
Customer_Segmentation 데이터셋은 고객 세분화 정보를 담고 있다.
| 변수 | 설명 |
|---|---|
| ID | 고객 ID 번호 |
| Gender | 성별 |
| Ever_Married | 결혼 여부 |
| Age | 나이 |
| Graduated | 대학 졸업 여부 |
| Profession | 직업 |
| Work_Experience | 근무년수 |
| Spending_Score | 지출 수준 |
| Family_Size | 가족 수(본인 포함) |
| Segmentation | 고객 세그먼트(A, B, C, D 중 하나) |
데이터
| ID | Segmentation |
|---|---|
| 462809 | D |
| 466315 | B |
| 461735 | B |
| 461319 | C |
| ID | Gender | Ever_Married | Age | Graduated | Profession | Work_Experience | Spending_Score | Family_Size |
|---|---|---|---|---|---|---|---|---|
| 462809 | Male | No | 22 | No | Healthcare | 1.0 | Low | 4.0 |
| 466315 | Female | Yes | 67 | Yes | Engineer | 1.0 | Low | 1.0 |
| 461735 | Male | Yes | 67 | Yes | Lawyer | 0.0 | High | 2.0 |
| 461319 | Male | Yes | 56 | No | Artist | 0.0 | Average | 2.0 |
주어진 훈련 데이터셋을 활용하여 고객이 속한 세그먼트(Segmentation)를
예측하고 해당 예측 결과를 다음과 같은 형식의 CSV 파일로 저장하시오.
(제출한 예측 결과의 macro_f1 결과에 따라 채점)
ID,Segmentation
1,A
2,A
3,C
...
추출된 텍스트가 원본과 일치하는지 확인 후 알려주세요! 😊
# 고객 데이터(Customer Segmentation) 분석을 위해 훈련 데이터(X_train, y_train)와 테스트 데이터(X_test)를 로드하고, 결측값 여부를 확인
import pandas as pd
X_test = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_X_test.csv')
X_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_X_train.csv')
y_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_y_train.csv')
print(X_train.head())## ID Gender Ever_Married ... Work_Experience Spending_Score Family_Size
## 0 462809 Male No ... 1.0 Low 4.0
## 1 466315 Female Yes ... 1.0 Low 1.0
## 2 461735 Male Yes ... 0.0 High 2.0
## 3 461319 Male Yes ... 0.0 Average 2.0
## 4 460156 Male No ... 1.0 Low 3.0
##
## [5 rows x 9 columns]
## X_train : 0
## y_train : 0
## X_test : 0
# 고객 데이터(Customer Segmentation)에서 범주형 데이터와 수치형 데이터를 분리하여, 각각의 특성에 맞는 처리를 준비하는 작업을 수행
# 데이터 나누기
# 범주형 데이터
X_train_word = X_train[['Gender','Ever_Married','Graduated','Profession' ,'Spending_Score']]
X_test_word = X_test[['Gender','Ever_Married','Graduated','Profession' ,'Spending_Score']]
print(X_train_word)## Gender Ever_Married Graduated Profession Spending_Score
## 0 Male No No Healthcare Low
## 1 Female Yes Yes Engineer Low
## 2 Male Yes Yes Lawyer High
## 3 Male Yes No Artist Average
## 4 Male No Yes Healthcare Low
## ... ... ... ... ... ...
## 6713 Male Yes Yes Artist High
## 6714 Male No No Executive Low
## 6715 Female No Yes Healthcare Low
## 6716 Female No Yes Healthcare Low
## 6717 Male Yes Yes Executive Average
##
## [6718 rows x 5 columns]
# 수치형 데이터
X_train_num= X_train.drop(columns=['ID','Gender','Ever_Married','Graduated','Profession','Spending_Score'])
X_test_num= X_test.drop(columns=['ID','Gender','Ever_Married','Graduated','Profession','Spending_Score'])
print(X_train_num)## Age Work_Experience Family_Size
## 0 22 1.0 4.0
## 1 67 1.0 1.0
## 2 67 0.0 2.0
## 3 56 0.0 2.0
## 4 32 1.0 3.0
## ... ... ... ...
## 6713 41 0.0 5.0
## 6714 35 3.0 4.0
## 6715 33 1.0 1.0
## 6716 27 1.0 4.0
## 6717 37 0.0 3.0
##
## [6718 rows x 3 columns]
# 수치형 데이터의 스케일링과 범주형 데이터의 원-핫 인코딩(One-Hot Encoding)을 수행한 후, 각각의 결과를 합쳐 최종 데이터프레임을 생성하는 작업을 수행
# 데이터 스케일링
from sklearn.preprocessing import MinMaxScaler
# MinMax 스케일러 생성
scaler = MinMaxScaler()
# 선택한 특성에 MinMax 스케일러를 적용하고 데이터 변환
X_train_num_scale = scaler.fit_transform(X_train_num)
X_test_num_scale = scaler.transform(X_test_num)
# 데이터 프레임 설정
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)
df_test_word = pd.get_dummies(X_test_word).astype(int)
# 데이터 결합
df_train = pd.concat([df_train_num, df_train_word], axis = 1)
df_test = pd.concat([df_test_num, df_train_word], axis = 1)
print(df_train)## Age Work_Experience ... Spending_Score_High Spending_Score_Low
## 0 0.056338 0.071429 ... 0 1
## 1 0.690141 0.071429 ... 0 1
## 2 0.690141 0.000000 ... 1 0
## 3 0.535211 0.000000 ... 0 0
## 4 0.197183 0.071429 ... 0 1
## ... ... ... ... ... ...
## 6713 0.323944 0.000000 ... 1 0
## 6714 0.239437 0.214286 ... 0 1
## 6715 0.211268 0.071429 ... 0 1
## 6716 0.126761 0.071429 ... 0 1
## 6717 0.267606 0.000000 ... 0 0
##
## [6718 rows x 21 columns]
# 고객 세분화(Customer Segmentation) 문제를 해결하기 위해 데이터 로드, 전처리, 모델 학습, 성능 평가
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.preprocessing import LabelEncoder
# 데이터 로드
X_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_X_train.csv')
X_test = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_X_test.csv')
y_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_y_train.csv')
# 결측값 확인
print(f"X_train 결측값: {X_train.isnull().sum().sum()}")## X_train 결측값: 0
## X_test 결측값: 0
## y_train 결측값: 0
# 타겟 데이터 변환
y_train['Segmentation'] = y_train['Segmentation'].map({'A': 0, 'B': 1, 'C': 2, 'D': 3}).copy()
# 범주형 데이터 인코딩
for col in ['Gender', 'Ever_Married', 'Graduated', 'Profession', 'Spending_Score']:
le = LabelEncoder()
X_train[col] = le.fit_transform(X_train[col])
X_test[col] = le.transform(X_test[col])
# 데이터 분리
X1_train, X1_val, y1_train_t, y1_val = train_test_split(
X_train, y_train['Segmentation'], test_size=0.3, random_state=77, stratify=y_train['Segmentation']
)
# 모델 생성 및 학습
model = xgb.XGBClassifier(random_state=77)
model.fit(X1_train, y1_train_t)XGBClassifier(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, objective='multi:softprob', ...)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. XGBClassifier(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, objective='multi:softprob', ...)## Classification Report:
## precision recall f1-score support
##
## 0 0.44 0.45 0.44 488
## 1 0.41 0.36 0.39 475
## 2 0.56 0.56 0.56 521
## 3 0.63 0.68 0.65 532
##
## accuracy 0.52 2016
## macro avg 0.51 0.51 0.51 2016
## weighted avg 0.51 0.52 0.52 2016
# 고객 세분화(Customer Segmentation) 문제를 해결하기 위해 데이터 로드, 전처리, 모델 학습, 예측, 결과 저장
import pandas as pd
import xgboost as xgb
from sklearn.preprocessing import LabelEncoder
# 데이터 로드
X_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_X_train.csv')
X_test = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_X_test.csv')
y_train = pd.read_csv('https://raw.githubusercontent.com/YoungjinBD/dataset/main/CS_Seg_y_train.csv')
# 타겟 데이터 변환
y_train['Segmentation'] = y_train['Segmentation'].map({'A': 0, 'B': 1, 'C': 2, 'D': 3}).copy()
# 범주형 데이터 인코딩
for col in ['Gender', 'Ever_Married', 'Graduated', 'Profession', 'Spending_Score']:
le = LabelEncoder()
X_train[col] = le.fit_transform(X_train[col])
X_test[col] = le.transform(X_test[col])
# 열 정렬 (훈련 데이터와 테스트 데이터의 열을 동일하게 맞춤)
X_test = X_test[X_train.columns]
# 모델 생성 및 학습
model = xgb.XGBClassifier(random_state=77)
model.fit(X_train, y_train['Segmentation'])XGBClassifier(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, objective='multi:softprob', ...)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. XGBClassifier(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, objective='multi:softprob', ...)# 예측
y_pred = model.predict(X_test)
# 결과를 데이터프레임으로 저장
df = pd.DataFrame(X_test['ID'], columns=['ID']) # 테스트 데이터의 ID
df['Segmentation'] = y_pred
# 숫자를 문자로 변환
df['Segmentation'] = df['Segmentation'].map({0: 'A', 1: 'B', 2: 'C', 3: 'D'})
# 결과 출력
print(df.head())## ID Segmentation
## 0 458989 B
## 1 458994 C
## 2 459000 C
## 3 459003 C
## 4 459005 D