→ 데이터 기반의 의사결정 가능
데이터를 분석하고 이를 바탕으로 결정을 내릴 수 있기 때문
통계를 활용한 데이터 분석은 필수!

→ 단순하게 비율 계산하는 것도 결국 통계임!






★ 중앙값도 '중간'을 얻어내는 거고 평균도 어떻게 보면 중간을 얻어내는 것 아닌가요? → 서로 느낌이 다릅니다!
★ 평균은 계산해서 얻은 중간, 중앙값은 크기 순서대로 정렬해서 딱 가운데에 있는 숫자
★ 시험 점수가 10 10 10 90 90 이면 평균은 42점 중앙값은 10점

→ 자료의 평균값·중앙값·최빈값이 거의 비슷하다면 <그림 3>의 ①과 같은 단봉분포가 된다. 단봉분포의 평균값은 대푯값으로써 의미가 있다.
반면 <그림 3>의 ②처럼 자료가 쌍봉분포라면 평균값만으로 자료를 판단하기에 부족하다.
또한 자료가 ‘최빈값 < 중앙값 < 평균값’ 형태를 취한다면 <그림 3>의 ③처럼 봉우리가 왼쪽으로 치우친 모습을, ‘평균값 < 중앙값 < 최빈값’ 형태라면 <그림 3>의 ④와 같이 오른쪽으로 치우친 모양을 갖는다.
예를 들어 시험 결과 저득점자가 극단적으로 많으면 왼쪽으로, 고득점자가 극단적으로 많으면 오른쪽으로 쏠린 형태의 분포가 나온다.
데이터 값들이 평균으로부터 얼마나 떨어져 있는지를 나타내는 척도
분산을 구하는 방법: 각 데이터 값에서 평균을 뺀 값을 제곱한 후, 이를 모두 더하고 데이터의 개수로 나눔
분산 계산 예시
→ cf. 정확도(accuracy)와 정밀도(precision)

데이터 값들이 평균에서 얼마나 떨어져 있는지를 나타내는 통계적 척도
데이터의 변동성을 측정하며, 값이 클수록 데이터가 평균으로부터 더 넓게 퍼져 있음을 의미
표준편차 계산 예시
→ 가지고 있는 정보를 바탕으로 우리가 접하지 않은 것에 대한 '추론'을 진행
(inference: a guess that you make or an opinion that you form based on the information that you have)
Inference is an act of drawing a conclusion based on evidence or reasoning, while a guess is an attempt to predict or estimate something without sufficient information.

# 데이터 분석에서 자주 사용되는 라이브러리
import pandas as pd
# 다양한 계산을 빠르게 수행하게 돕는 라이브러리
import numpy as np
# 시각화 라이브러리
import matplotlib.pyplot as plt
# 시각화 라이브러리2
import seaborn as sns
data = [85, 90, 78, 92, 88, 76, 95, 89, 84, 91]
data_mean = np.mean(data)
data_median = np.median(data)
print(f'평균: {data_mean}, 중앙값:{data_median}')
data_variance = np.var(data)
data_std_dev = np.std(data)
data_range = np.max(data) - np.min(data)
print(f'분산: {data_variance}, 표준편차: {data_std_dev}, 범위: {data_range}')
plt.hist(data, bins=5)
plt.title('histogram')
plt.show()

plt.boxplot(data)
plt.title('box plot')
plt.show()

bins=5 더 알아보기bins=: 데이터를 몇 개의 구간으로 쪼개어(계급을 나누어) 히스토그램을 그릴지 설정하는 옵션bins=n: n개의 동일한 width를 갖는 bin을 생성하겠다는 뜻10plt.hist(data)
plt.title('compare')
plt.show()

→ 구간의 개수에 따라 히스토그램 분포의 형태가 달라질 수 있음
→ 적절한 구간의 개수를 지정해야 함!

weight = [68, 81, 64, 56, 78, 74, 61, 77, 66, 68, 59, 71,
80, 59, 67, 81, 69, 73, 69, 74, 70, 65]
plt.hist(weight, label='bins=10')
plt.hist(weight, bins=30, label='bins=30')
plt.legend()
plt.show()

satisfaction = ['satisfaction', 'satisfaction', 'dissatisfaction',
'satisfaction', 'dissatisfaction', 'satisfaction', 'satisfaction',
'dissatisfaction', 'satisfaction', 'dissatisfaction']
satisfaction_counts = pd.Series(satisfaction).value_counts()
satisfaction_counts.plot(kind='bar')
plt.title('satisfaction distribution')
plt.show()
.value_counts()는 개수 세는 것임

satisfaction_counts.plot(kind='pie')
plt.title('satisfaction distribution: pie')
plt.show()
plt.pie(satisfaction_counts)
plt.title('satisfaction distribution: pie (2)')
plt.show()
colours = sns.color_palette('colorblind6')
plt.pie(satisfaction_counts, labels=satisfaction_counts.index, colors=colours, autopct='%.0f%%')
plt.title('satisfaction distribution: pie (3)')
plt.show()



wedgeprops={'width': 0.7, 'edgecolor': 'w', 'linewidth': 5}
plt.pie(satisfaction_counts, labels=satisfaction_counts.index, colors=colours, autopct='%.0f%%', wedgeprops=wedgeprops, startangle=180)
plt.title('satisfaction distribution: pie (4)')
plt.show()

데이터들끼리 서로 관련이 있는지 확인
두 변수 간의 관계를 측정
-1이나 1에 가까워지면 강력한 상관관계-0.5나 0.5를 가지면 중간 정도의 상관관계0에 가까울수록 상관관계가 없음산점도(Scatter plot)

(예) 공부 시간과 시험 점수 간의 상관관계를 분석
study_hours = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
exam_scores = [95, 90, 85, 80, 75, 70, 65, 60, 55, 50]
correlation = np.corrcoef(study_hours, exam_scores)[0, 1]
print(f"공부 시간과 시험 점수 간의 상관계수: {correlation}")
plt.scatter(study_hours, exam_scores)
plt.show()
correlation = np.corrcoef(study_hours, exam_scores)[0, 1]에서 [0, 1] 의미

np.corrcoef()
피어슨 상관계수

np.corrcoef() vs. df.corr()
x = np.array([[0, 2, 7], [1, 1, 9], [2, 0, 13]]).T
x_df = pd.DataFrame(x)
print("matrix:")
print(x)
print()
print("df:")
print(x_df)
print()
print("np correlation matrix: ")
print(np.corrcoef(x))
print()
print("pd correlation matrix: ")
print(x_df.corr())
print()
→ Why the numpy correlation coefficient matrix and the pandas correlation coefficient matrix different when using np.corrcoef(x) and df.corr()?
matrix:
[[ 0 1 2]
[ 2 1 0]
[ 7 9 13]]
df:
0 1 2
0 0 1 2
1 2 1 0
2 7 9 13
np correlation matrix:
[[ 1. -1. 0.98198051]
[-1. 1. -0.98198051]
[ 0.98198051 -0.98198051 1. ]]
pd correlation matrix:
0 1 2
0 1.000000 0.960769 0.911293
1 0.960769 1.000000 0.989743
2 0.911293 0.989743 1.000000
np.corrcoef(x.T)==x_df.corr() or print(np.corrcoef(x, rowvar=False))
You are taking a different set of numbers in the correlation coefficients.
Think about it in a 2x3 matrix:
x = np.array([[0, 2, 7], [1, 1, 9]])
np.corrcoef(yx)
gives
array([[1. , 0.96076892],
[0.96076892, 1. ]])
and
x_df = pd.DataFrame(yx.T)
print(x_df)
x_df[0].corr(x_df[1])
gives
0 1
0 0 1
1 2 1
2 7 9
0.9607689228305227
where the 0.9607... etc numbers match the output of the NumPy calculation.
If you do it the way in your calculation it is equivalent to comparing the correlation of the rows rather than the columns. You can fix the NumPy version using .T or the argument rowvar=False
corr와 np.corrcoef() 차이 비교의 내용에 따르면 NULL값에 따른 민감도 차이가 있다고 함
data = {'TV': [230.1, 44.5, 17.2, 151.5, 180.8],
'Radio': [37.8, 39.3, 45.9, 41.3, 10.8],
'Newspaper': [69.2, 45.1, 69.3, 58.5, 58.4],
'Sales': [22.1, 10.4, 9.3, 18.5, 12.9]}
df = pd.DataFrame(data)
sns.pairplot(df)
plt.show()
# heatmap까지 그린다면
sns.heatmap(df.corr())
plt.show()


