[Python] 통계 및 머신러닝 과제

yeji·2024년 12월 10일

Python

목록 보기
31/36

Q1.

  • statistics csv 파일을 읽고, 성별 Review Rating 에 대한 평균과 중앙값을 구해주세요. 결과는 소수점 둘째자리까지 표현해주세요.
  • 그리고 이에 대한 해석을 간략하게 설명해주세요.
# 라이브러리
import pandas as pd
import numpy as np 
import scipy.stats as stats
from datetime import datetime, timedelta

# 데이터 가져오기
df = pd.read_csv("/Users/t2023-m0092/Desktop/J/Python/세션/세션_전소현 튜터/머신러닝/과제/statistics.csv")

# 데이터 확인
df.head()

# 평균
df.groupby(['Gender'])['Review Rating'].mean().round(2)

# 중앙값
df.groupby(['Gender'])['Review Rating'].median().round(2)

Q2.

  • 성별, Review Rating 컬럼에 대한 T-TEST 를 진행해주세요.
    • 귀무가설과 대립가설을 작성해주세요.
    • t-score, P-value 를 구해주세요.
    • 그리고 이에 대한 귀무가설 채택/기각 여부와 그렇게 생각한 이유를 간략하게 설명해주세요.
# 귀무가설: 남성과 여성의 평균 별점에 차이가 없을 것이다. 
# 대립가설: 남성과 여성의 평균 별점에 차이가 있을 것이다.

# 데이터 분리
mask=(df['Gender']=='Male')
mask1 = (df['Gender']=='Female')

m_df = df[mask]
f_df = df[mask1]

# 별점 컬럼만 가져오기 
m_df=m_df[['Review Rating']]
f_df=f_df[['Review Rating']]

# t-test
t, pvalue=stats.ttest_ind(f_df, m_df)

# 결과 확인
t, pvalue

Q3.

  • Color, Season 컬럼에 대한 카이제곱 검정을 진행해주세요.
    • 귀무가설과 대립가설을 작성해주세요.
    • 두 범주형 자료의 빈도표를 만들어주세요. 이를 코드로 작성하여 기재해주세요.
    • 카이제곱통계량, P-value 를 구해주세요.
    • 그리고 이에 대한 귀무가설 채택/기각 여부와 그렇게 생각한 이유를 간략하게 설명해주세요.
# 귀무가설: Color와 Season 에는 관련성이 없을 것이다. (독립적일 것이다)
# 대립가설: Color와 Season 에는 관련성이 있을 것이다.

# 실제 데이터 비교
df.groupby(['Color', 'Season'])['Customer ID'].count().reset_index()

# 빈도표
result = pd.crosstab(df['Color'], df['Season'])
result

# 카이제곱검정
stats.chi2_contingency(observed=result)

# 카이제곱 통계량
stats.chi2_contingency(observed=result)[0]

# p-value
stats.chi2_contingency(observed=result)[1]

Q4.

  • 아래와 같은 데이터가 있다고 가정하겠습니다.데이터를 바탕으로 선형 회귀 모델을 훈련시키고, 회귀식을 작성해주세요.
    • 독립 변수(X): 광고예산 (단위: 만원)
    • 종속 변수(Y): 일일 매출 (단위: 만원)
    • X=[10, 20, 30, 40, 60, 100]
    • Y=[50, 60, 70, 80, 90, 120]
  • 회귀식을통해, 새로운 광고예산이 1,000만원일 경우의 매출을 예측(계산)해주세요.
# 라이브러리
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# 변수 설정
X = [[10], [20], [30], [40], [60], [100]]
Y = [50, 60, 70, 80, 90, 120]

# 모델 생성
model = LinearRegression()

# 모델 훈련
model.fit(X, Y)

# 회귀 계수, 절편 확인
coef = model.coef_[0]
intercept = model.intercept_

# 회귀식(소수점 둘째자리까지 표시)
print(f"회귀식 : Y = {coef:.2f}X + {intercept:.2f}")

# 예측
x_pred = 1000
y_pred = model.predict([[x_pred]])[0]
print(f"광고예산이 {x_pred}만원일 경우 예상 매출은 {y_pred:.2f}만원")

Q5.

  • Review Rating, Age, Previous Purchases 컬럼을 활용하여, 고객이 할인(Discount Applied)을 받을지 예측하는 RandomForest모델을 학습시켜 주세요. 그리고 모델 정확도를 계산해주세요.
    • y(종속변수)는 Yes/No 로 기재된 이진형 데이터입니다. 따라서, 인코딩 작업이 필요합니다. 구현을 위해 LabelEncoder를 사용해주세요.
    • 머신러닝시, 전체 데이터셋을 Train set과 Test set 으로 나눠주세요. 해당 문제에서는Test set비중을 30%로 설정해주세요. random_state는 42로 설정해주세요.
# 라이브러리
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score,f1_score

# 라벨인코딩
le = LabelEncoder()
le.fit(df[['Discount Applied']])
# 변환 후 컬럼 추가
df['Discount Applied_le'] = le.transform(df[['Discount Applied']])

# 변수 설정
X_rf = df[['Review Rating', 'Age', 'Previous Purchases']]
Y_rf = df['Discount Applied_le']

# 데이터 분리
X_train, X_test, Y_train, Y_test = train_test_split(X_rf, Y_rf, test_size=0.3, random_state=42)

# 모델 생성
model_rf = RandomForestClassifier(random_state=42)

# 모델 학습
model_rf.fit(X_train, Y_train)

# 예측
Y_pred_rf = model_rf.predict(X_test)

# 평가 함수 정의
def get_score(model_name, y_true, y_pred):
    acc = accuracy_score(y_true, y_pred).round(3)
    f1 = f1_score(y_true,y_pred).round(3)
    print(model_name, 'acc 스코어 : ',acc, 'f1_score : ', f1)

# 평가
get_score('rf', Y_test, Y_pred_rf)

Q6.

  • Subscription Status 컬럼을 종속변수로 사용하여 고객의 이탈 여부를 예측하는 로지스틱 회귀 모델 학습을 진행해주세요. Age, Purchase Amount, Review Rating을 활용하여 모델을 훈련한 후, 연령 30세, 구매 금액 50 USD, 리뷰 평점 4.0인 고객의 이탈 확률을 계산해주세요.
    • y(종속변수)는 Yes/No 로 기재된 이진형 데이터입니다. 따라서, 인코딩 작업이 필요합니다. 구현을 위해 LabelEncoder를 사용해주세요.
    • 머신러닝시, 전체 데이터셋을 Train set과 Test set 으로 나눠주세요. 해당 문제에서는Test set비중을 30%로 설정해주세요. random_state는 42로 설정해주세요.
      • Train Set: 모델을 학습하는데 사용하는 데이터셋
      • Test Set: 적합된 모델의 성능을 평가하는데 사용하는 데이터셋
    • 연령 30세, 구매 금액 50 USD, 리뷰 평점 4.0 인 고객을 new_customer 라는 변수에 지정해주세요. 1차원이 아닌 이중 대괄호[[...]]로 지정해주세요. (모델 입력 형식은 2차원 배열이어야 하므로)
    • model.predict_proba 를 사용하여 이탈 확률을 구해주세요.
      • predict_proba의 반환값: 모델이 각 클래스에 속할 확률을 계산합니다. 결과는 다음과 같은 배열로 반환됩니다.
      • [[P(클래스 0), P(클래스 1)]]
      • P(클래스 0): 이 고객이 이탈하지 않을 확률
      • P(클래스 1): 이 고객이 이탈할 확률
# 라이브러리
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score

# 라벨인코딩
le = LabelEncoder()
le.fit(df[['Subscription Status']])
# 변환 후 컬럼 추가
df['Subscription Status_le'] = le.transform(df[['Subscription Status']])

# 변수 설정
X_lr = df[['Age', 'Purchase Amount (USD)', 'Review Rating']]
Y_lr = df[['Subscription Status_le']]

# 데이터 분리
X_train_lr, X_test_lr, Y_train_lr, Y_test_lr = train_test_split(X_lr, Y_lr, test_size=0.3, random_state=42)

# 모델 생성
model_lr = LogisticRegression()

# 모델 학습
model_lr.fit(X_train_lr, Y_train_lr)

# 예측
Y_pred_lr = model_lr.predict(X_test_lr)

# 평가 함수 정의
def get_score(model_name, y_true, y_pred):
   acc = accuracy_score(y_true, y_pred).round(3)
   f1 = f1_score(y_true,y_pred).round(3)
   print(model_name, 'acc 스코어 : ',acc, 'f1_score : ', f1)

# 평가
get_score('lr', Y_test_lr, Y_pred_lr)

# 새로운 변수 생성
filter = df[(df['Age']>=30) & (df['Purchase Amount (USD)']>=50) & (df['Review Rating'] >=4)]

# 2차원으로 변환
new_customer = filter[['Age', 'Purchase Amount (USD)', 'Review Rating']]

# 이탈 확률
proba = model_lr.predict_proba(new_customer)

# 확인
proba

-> 새로운 변수가 해당 조건 이상이 아니라 저기에 해당하는 것!
-> 아래 부분만 틀림,,,ㅜㅜ

# 새로운 변수 생성
new_customer = [[30, 50, 4.0]]

# 예측
proba = model_lr.predict_proba(new_customer)[0, 1]

# 확인
print(f"연령 30세, 구매 금액 50, 리뷰 평점이 4.0인 고객의 이탈 확률 : {proba:.4f}")
profile
👋🏻

0개의 댓글