본문 바로가기
AI

Day63_Ai(1)_Am / 머신러닝 가기전 최소한의 수학

by roaring90s 2025. 10. 27.

data 해석

 

mathEx1

import numpy as np
import pandas as pd

df = pd.read_csv('ch2_scores_em.csv', index_col='student number')
print(df)
df.info()
print()

scores = np.array(df['english'])[:10]
print(scores)
print()

scores_df = pd.DataFrame({'score':scores},
                         index=pd.Index(list('ABCDEFGHIJ'),name='student'))
print(scores_df)
print()

# 중앙값 구하기
sorted_scored = np.sort(scores)
print(sorted_scored)

n = len(sorted_scored)
#먼저 소팅을 시킨후
if n % 2 == 0:
    m0 = sorted_scored[n // 2 - 1]
    m1 = sorted_scored[n // 2]
    median = (m0 + m1) / 2
else:
    median = sorted_scored[(n+1)//2 - 1]

print(median)
print(np.median(scores))
print(scores_df.median())
print()

 


 

#편차
mean = np.mean(scores)
print(mean)
deviation = scores - mean
print(deviation)
print()

값만 보는게 아니라 이 값들이 어떻게 분포되어있는지 확인 = 편차

 

another_scores = [50, 60, 58, 54, 51, 56, 57, 53, 67, 59]
another_mean = np.mean(another_scores)
print(another_mean)
another_deviation = another_scores - another_mean
print(another_deviation)
print(np.mean(another_deviation))
print()

 


 

🎈매우 중요!🎈

분산이 작다는건 평균 근처에 데이터들이 모여 잇다 라는것

분산이 크다라는건 평균으로 부터 데이터들이 많이 떨어져 있다 라는 의미

 

#분산
summary_df = scores_df.copy()
summary_df['deviation'] = deviation
print(np.mean(deviation ** 2))
print(np.var(scores))
print(scores_df.var())
# 실제 전체 데이터가 가지고 있는 데이터보다 작게 나온다. ( 과소평과 )
# 불편분산(언바이어스) 된 형태 [평향되지 않는]    

데이터를 다루지 못한다면 ai를 다루지 못한다.

실제로 현업에서 일을 할 시 데이터가 잘 돌아가는건 진짜 운이 좋은것.

[다루기 어렵네 ? == 무식한것 ]

print(scores_df.var(ddof=0))
# delta degree of freedom

 


 

print(np.sqrt(np.mean(deviation**2)))

 

 

 

 


 

 

 

 


 

 

 


 

mathEx2

수치가 2가지가 있는데

특정데이터가 얼마나 떨어져 있는지?

편차와 편차 사이의 영역에 공분

 

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv('ch2_scores_em.csv', index_col='student number')
print(df)

en_scores = np.array(df['english'])[:10]
ma_scores = np.array(df['mathematics'])[:10]
scores_df = pd.DataFrame({'english':en_scores,
                          'mathematics':ma_scores},
                         index=pd.Index(list('ABCDEFGHIJ'), name='student'))
print(scores_df)

summary_df = scores_df.copy()
summary_df['english_deviation'] = summary_df['english'] - summary_df['english'].mean()
summary_df['mathematics_deviation'] = summary_df['mathematics'] - summary_df['mathematics'].mean()
summary_df['product_of_deviation'] = summary_df['english_deviation'] * summary_df['mathematics_deviation']
print(summary_df)
print()
print(summary_df['product_of_deviation'].mean())
print(np.cov(en_scores, ma_scores, ddof=0))

피어슨 상관계수

분산에 대한 값이 커진다 1에서 0으로 갈 수록

-1 에서 0으로 갈 수록 분산에 대한 값이 커진다.

#상관계수

print(round(np.cov(en_scores, ma_scores, ddof=0)[0,1]/ (np.std(en_scores) * (np.std(ma_scores))), 3))
print(np.corrcoef(en_scores, ma_scores))
print(scores_df.corr())

y= ax + b / a는 기울기 

poly_fit = np.polyfit(en_scores, ma_scores, deg=1)#deg = 차원수 몇차원인지
print(poly_fit)

0.7이 a값 31.이 b값

poly_fit = np.polyfit(en_scores, ma_scores, deg=1)#deg = 차원수 몇차원인지
print(poly_fit)

poly_1d = np.poly1d(poly_fit)
print(poly_1d)

xs = np.linspace(en_scores.min(), en_scores.max(), 50)
print(xs)
#xs 값이 y= ax+b 에 x 값
ys = poly_1d(xs)

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
ax.scatter(en_scores, ma_scores, label='scores')
ax.plot(xs, ys, color='gray', label=f'{poly_fit[0]}x + {poly_fit[1]:.2f}')
ax.legend(loc='best')
ax.set_xlabel('english')
ax.set_ylabel('mathmatics')
plt.show()

상관계수와 분산에 대해 무조건 알고 잇어야 한다. + 정규화 했던거 의미를 확실하게 

더하기는 평균위치를 옮겨준다.

곱하기 편차값의 폭을 조절

사분위 

'AI' 카테고리의 다른 글

Day65_Ai(3)_Pm  (0) 2025.10.29
Day65_Ai(3)_Am  (0) 2025.10.29
Day64_Ai(2)_Pm  (0) 2025.10.28
Day64_Ai(2)_Am  (0) 2025.10.28
Day63_Ai(1)_Pm  (0) 2025.10.27