NumPy Master Class

Chapter2 Arithmetic Operations: Notebook5 Mean, Std and Var Values

Shin's Lab 2020. 1. 8. 19:54
2_5_Mean_Std_Var_Values

NumPy Master Class

Chapter2 Arithmetic Operations

Notebook5 Mean, Std, Var values

우리가 data를 분석할 때 가장 먼저 사용하는 값들이 바로 mean, standard deviation, variance 값들이다.

물론 NumPy에서도 이를 쉽게 구할 수 있는 method들이 존재한다. 이들은 각각

1. ndarray.mean()
2. ndarray.std()
3. ndarray.var()

이다.

In [8]:
import numpy as np

ndarray.mean(), ndarray.std(), ndarray.var() with 1-dim ndarray

In [7]:
test_np = np.random.randint(low = 0, high = 100, size = (200,))

print("mean:", test_np.mean())
print("standard deviation: ", test_np.std())
print("variance:", test_np.var())
mean: 48.55
standard deviation:  29.587624101978854
variance: 875.4275

이를 이용하면 data에 대한 통계적 처리가 훨씬 수월해진다.

실제 예를 들기 위해 우리의 수학, 영어, 물리 성적을 가져와보자.


ndarray.mean(), ndarray.std(), ndarray.var() with 2-dim ndarray

이제 2차원 ndarray를 이용하여 mean, std, var를 구해보고 실제 수능과 같은 시험에서 사용되는 표준점수를 환산하는 과정을 살펴보자.

In [11]:
import pandas as pd
maths = np.random.randint(low = 30, high = 100, size = (20,))
english = np.random.randint(low = 30, high = 100, size = (20,))
physics = np.random.randint(low = 30, high = 100, size = (20,))

score_table = np.vstack((maths, english, physics)).T
d = {"Math scores": maths, "English scores": english, "Physics scores": physics}
df = pd.DataFrame(data=d)
print(df)
    Math scores  English scores  Physics scores
0            41              93              38
1            46              69              98
2            62              63              44
3            66              32              55
4            33              76              85
5            40              88              83
6            52              84              63
7            36              49              63
8            41              63              34
9            64              68              73
10           87              40              89
11           62              73              50
12           48              31              90
13           66              57              69
14           34              49              86
15           51              53              62
16           41              32              91
17           90              85              46
18           85              61              82
19           72              63              66

우리가 mean, std, var를 구하는 과정은 과목별로 구하게 되므로 axis=0이 되는 것을 알 수 있고,

이는 각각 다음과 같다.

In [16]:
mean_np = score_table.mean(axis = 0)
std_np = score_table.std(axis = 0)

print("mean values:", mean_np)
print("std values:", std_np)
mean values: [55.85 61.45 68.35]
std values: [17.4621734  18.35612977 18.85543688]

이때 slicing을 이용하여 각 점수들을 추출해보면

In [21]:
print(score_table.shape)
(20, 3)

위와 같이 현재 20명에 대한 각각의 과목별 점수를 가지고 있다.

그리고 표준점수를 환산하는 공식은 다음과 같다.

표준점수 = $20*\frac{원점수- 과목평균}{과목표준편차} + 100$

구체적인 이유는 중요한 것이 아니므로 이 표준점수를 구하는 과정에 집중해보도록 하자

먼저 dimension을 살펴보면 다음과 같다.

In [22]:
print(score_table.shape)
print(mean_np.shape)
print(std_np.shape)
(20, 3)
(3,)
(3,)

그리고 우리가 배운 broadcasting을 이요하면

score_table - mean_np

를 하면 mean_np는 (20,3)로 broadcasting되어 각각의 element에 element-wise로 빼지는 것을 알 수 있다.

In [24]:
mean_sub = score_table - mean_np
print(mean_sub.shape)
(20, 3)

물론 이 결과는 다시 (20,3)의 ndarray를 가지게 되고, 우리가 여기에 std_np를 나눠준다면 다시 이 std_np는 (20,3)으로 broadcasting되어 나눠지는 것을 알 수 있다.

In [26]:
std_div = (score_table - mean_np)/std_np
print(std_div.shape)
(20, 3)

그리고 우리가 matrix와 scalar의 연산에서의 broadcasting을 이용하여 20을 곱해주고, 100을 더해주면

원하는 표준점수의 ndarray를 구할 수 있다.

In [28]:
standard_scores = 20*(score_table - mean_np)/std_np + 100
print(standard_scores.shape)
(20, 3)

이렇게 ndarray를 이용하면 한 줄을 통해 큰 matrix에 연산도 가능해지는 것을 알 수 있다.