✍나의 답
# 라이브러리 호출
import pandas as pd
import numpy as np
# 과학 계산용 파이썬 라이브러리
import scipy.stats as stats
import warnings
warnings.filterwarnings('ignore')
df = pd.read_csv("statistics.csv")
# Review Rating 에 대한 평균
mean = df.groupby(['Gender'])['Review Rating'].mean().round(2)
# Review Rating 에 대한 중앙값
median = df.groupby(['Gender'])['Review Rating'].median().round(2)
print(f"평균: {mean}")
print(f"중앙값: {median}")

✍튜터님 답
df.groupby(['Gender'])['Review Rating'].agg(['mean','median']).round(2).reset_index()

✍나의 답
# 데이터 분리
# mask method
mask=(df['Gender']=='Male')
mask1 = (df['Gender']=='Female')
m_rr =df[mask]
f_rr =df[mask1]
# 별점 컬럼만 가져오기
m_rr=m_rr[['Review Rating']]
f_rr=f_rr[['Review Rating']]
# t-test
t, pvalue = stats.ttest_ind(f_rr, m_rr)
#결과 출력
print(f"t-score: {t}")
print(f"p-value: {pvalue}")

✍튜터님 답
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, pvalue=stats.ttest_ind(f_df, m_df)
t, pvalue

✍나의 답
#빈도표 만들기
result = pd.crosstab(df['Color'],df['Season'])
#카이제곱검정
stats.chi2_contingency(observed=result)
#검정통계량
Chi_square = stats.chi2_contingency(observed=result)[0]
#p-value
p_value = stats.chi2_contingency(observed=result)[1]
#결과 출력
print(f"검정통계량: {Chi_square:.2f}")
print(f"p-value: {p_value:.2f}")

✍튜터님 답
result = pd.crosstab(df['Color'], df['Season'])
stats.chi2_contingency(observed=result)

✍나의 답
import numpy as np
from sklearn.linear_model import LinearRegression
#데이터 정의
X = np.array([10, 20, 30, 40, 60, 100])
y = np.array([50, 60, 70, 80, 90, 120])
# 1차원 -> 2차원 변경
X = X.reshape(-1, 1)
# 단순선형회귀 모델 선언
model = LinearRegression()
# 모델 학습
model.fit(X, y)
# 회귀 계수와 절편
W = model.coef_ # 회귀 계수
b = model.intercept_ # 절편
# 새로운 광고 예산
ad = 1000
# 회귀식을 사용하여 예측
predict = W * ad + b
print(W)
print(b)
print(f"예상 매출 : {predict}")

✍튜터님 답
from sklearn.linear_model import LinearRegression
# 데이터
X = np.array([10, 20, 30, 40, 60, 100]).reshape(-1, 1)
Y = np.array([50, 60, 70, 80, 90, 120])
# 모델 훈련
model = LinearRegression()
model.fit(X, Y)
# 회귀식
coef, intercept = model.coef_[0], model.intercept_
print(f"회귀식: Y = {coef:.2f}X + {intercept:.2f}")
# 예측
predicted_sales = model.predict(np.array([[1000]]))
print(f"1000만원 광고비일 때 예상 매출: {predicted_sales[0]:.2f}만원")

✍나의 답
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
#라벨인코딩
le = LabelEncoder()
df['Discount Applied'] = le.fit_transform(df['Discount Applied'])
#데이터 정의
X = df[['Review Rating', 'Age', 'Previous Purchases']]
y = df['Discount Applied']
# 학습 데이터와 테스트 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 랜덤포레스트 모델 선언
rf_model = RandomForestClassifier(random_state=42)
#모델 학습
rf_model.fit(X_train, y_train)
# 예측 및 정확도 계산
accuracy = rf_model.score(X_test, y_test)
print(f"모델 정확도: {accuracy:.2f}")
# 모델 정확도 확인하는 다른 방법
# y_pred = rf_model.predict(X_test)
# accuracy = accuracy_score(y_test, y_pred)

✍튜터님 답
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
# 데이터 준비
X = df[['Review Rating', 'Age', 'Previous Purchases']]
y = LabelEncoder().fit_transform(df['Discount Applied'])
# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 모델 학습
rf_model = RandomForestClassifier(random_state=42)
rf_model.fit(X_train, y_train)
# 예측
accuracy = rf_model.score(X_test, y_test)
print(f"모델 정확도: {accuracy:.2f}")

[[...]]로 지정해주세요. (모델 입력 형식은 2차원 배열이어야 하므로)✍나의 답
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
#라벨인코딩
le = LabelEncoder()
df['Subscription Status'] = le.fit_transform(df['Subscription Status'])
#데이터 정의
X = df[['Age', 'Purchase Amount (USD)', 'Review Rating']]
y = df['Subscription Status']
# 학습 데이터와 테스트 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 로지스틱회귀 모델 선언
Log_model=LogisticRegression()
# 모델 학습
Log_model.fit(X_train, y_train)
# 고객에 대한 변수 지정
new_customer = pd.DataFrame([[30,50,4.0]])
# 이탈확률 구하기
predict_customer = Log_model.predict_proba(new_customer)
prob1 = predict_customer[0][0]
prob2 = predict_customer[0][1]
print(f"{prob1:.2f}: 고객이 이탈하지 않을 확률입니다.")
print(f"{prob2:.2f}: 고객이 이탈할 확률입니다.")

✍튜터님 답
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
# 데이터 준비
X = df[['Age', 'Purchase Amount (USD)', 'Review Rating']]
y = LabelEncoder().fit_transform(df['Subscription Status'])
# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 모델 학습
model = LogisticRegression()
model.fit(X_train, y_train)
# 새로운 데이터 예측
new_customer = [[30, 50, 4.0]]
predicted_prob = model.predict_proba(new_customer)[0, 1]
print(f"연령 30세, 구매 금액 50, 리뷰 평점 4.0인 고객의 이탈 확률: {predicted_prob:.4f}")
