-
11. mathematical functions공부/likelion 2021. 10. 19. 21:45
목차
1. 상수
2. 삼각함수
3. 지수함수
4. 쌍곡선 함수
5. 2차 함수
6. Irrational Function(무리 함수)
7. 유리 함수
8. 멱함수
9. 로그함수(목차를 보면 알겠지만, numpy가 많이 쓰이는 라이브러리인 이유를 알 수 있다.)
1. 상수
PI = np.pi E = np.e print("pi: ", PI) print("natural constant: ", E)
상수, 즉, 변하지 않는 수인 파이와 자연로그의 밑(base of the natural logarithm)을 numpy에서 제공한다.
물론 무리수이기 때문에 무리수 전체를 구현하지는 않은 것으로 추측할 수 있다.degree = np.array([30, 45, 60, 90, 180, 360]) rad = np.deg2rad(degree) degree = np.rad2deg(rad) print("radian: ", rad.round(3)) print("degree again: ", degree)
def2rad 와 rad2deg는 서로 반대되는 기능을 가지고 있는 함수로,
각각 단위에서 degree 는 각도, radian은 라디안 단위를 가리킨다.1 radian = 180 / π 이며, 1degree (1도) = (π * rad) / 180 이다.[1]
군대때 배운 mil(밀)은 밀리라디안의 줄임말로 1/1000 라디안을 나타낸다.[2]
2. 삼각함수
#Trigonometric Functions / 삼각함수 x = np.deg2rad(np.linspace(0, 360, 11)) sin, cos = np.sin(x), np.cos(x) tan = np.tan(x) print(f"np.tan: \n {tan.round(2)}") print(f"np.sin/np.cos: \n {(sin/cos).round(2)}")
기본적인 삼각함수인 sin, cos, tan 또한 numpy에는 구현이 되어있다.
코드에서는 linspace를 이용해서 간격을 구한다음, 해당 수들을 각각 함수에 넣어 값을 구하였다.2-1. 삼각함수 시각화
import matplotlib.pyplot as plt PI = np.pi x = np.linspace(0, 4*PI, 100) fig, ax = plt.subplots(figsize=(10, 5)) sin, cos, tan = np.sin(x), np.cos(x), np.tan(x) fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(x, sin, label = r'$y = sin(x)$') ax.plot(x, cos, label = r'$y = cos(x)$') ax.plot(x, tan, label = r'$y = tan(x)$') xticks = np.arange(0, 4*PI+0.1, 0.5*PI) xticklabels = [str(xtick)+r'$\frac{\pi}{2}$' for xtick in range(9)] ax.set_xticks(xticks) ax.set_xticklabels(xticklabels) ax.tick_params(axis='x', labelsize=20) ax.set_ylim([-2,2]) ax.legend()
3. 지수함수
E = np.e x = np.arange(1, 7) print(f"E**x: \n {(E**x).round(2)}") print(f"np.exp(x): \n {np.exp(x).round(2)}")
np.e를 통해서 자연상수 e를 얻었으니, 해당 함수를 이용해서 자연상수를 사용하는 지수함수를 구할 수 있다.
이를 시각화해보면 우리가 흔히 아는, 지수함수의 그래프, 로그함수의 역함수가 그려진다.
x = np.linspace(0, 5, 100) exp = np.exp(x) fig, ax = plt.subplots(figsize = (10,5)) ax.plot(x,exp) ax.tick_params(labelsize =20)
3-1. sigmoid (시그모이드)
위에서 언급했었던 지수함수를 이용해서 시그모이드 함수를 구할 수 있는데, 시그모이드의 특징은 다음과 같다.
- Logistic 함수이다.
- 모든 실수 값을 입력했을 때, 일반적으로 0~1 사이의 값을 반환한다.
즉 확률 형태인 값을 반환하며 이 때문에 가설 및 비용 함수(cost function)에 쓰인다.
(가끔 -1 ~ 1까지의 범위를 가지기도 한다) - 딥러닝에서는 임계값을 넘을 때만 출력되는 활성화 함수로도 쓰였다.
단, 음수값을 0에 가깝게 표현하기 때문에 경사 소실 문제가 발생해서 현재는 많이 쓰이지 않는 편이다.\ - S자 형태로, 매끄러운 형태의 연속함수이다.
- 오차함수(erf)와 이후에 설명할 쌍곡선 함수 중 tanh가 이러한 형태이다.
특히 3번과 관련하여 역전파(back propagation)를 구하는 과정에서 활성화 함수의 미분값을 곱해야하는데, 시그모이드를 활성화 함수로 할 경우, 미분 계수의 최대값이 0.25이기 때문에, layer(층)이 깊어지면 깊어질수록 그 계수가 점점 작아져서 오차율 계산이 어려워진다.
간단히 말하자면 미분 계수의 범위값이 0 ~ 0.25밖에 나오질 않으니,
최댓값을 대표값으로, 층의 갯수를 x라고 할 때 대략 다음과 같은 수식이 성립한다.따라서 x가 커지면 커질수록 그 값은 0에 가까워지니, 해당 값이 계산하기 어려워지는 것으로 생각하면 될 것 같다.
시그모이드의 그래프는 다음과 같다.
x = np.linspace(-5, 5, 100) sigmoid = 1/(1 + np.exp(-x)) fig, ax = plt.subplots(figsize = (10,5)) ax.plot(x,sigmoid) ax.tick_params(labelsize =20)
4. 쌍곡선 함수
#Hyperbolic Functions x = np.linspace(0, 1, 5) sinh, cosh = np.sinh(x), np.cosh(x) tanh = np.tanh(x) print(f"np.tanh: \n {tanh.round(2)}") print(f"np.sinh/np.cosh: \n {(sinh/cosh).round(2)}")
numpy에서는 쌍곡선 함수도 제공한다. 이러한 쌍곡선 함수와 관련해서는 참고자료를 읽어보자.[3][4]
x = np.linspace(0, 1, 5) sinh = np.sinh(x) sinh_exp = (np.exp(x) - np.exp(-x)) / 2 cosh = np.cosh(x) cosh_exp = (np.exp(x) - np.exp(-x)) / 2 tanh = np.tanh(x) tanh_exp = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) # cosh / sinh print(f"sinh: {sinh.round(2)}") print(f"sinh_exp: {sinh_exp.round(2)}\n") print(f"cosh: {cosh.round(2)}") print(f"cosh_exp: {cosh_exp.round(2)}\n") print(f"tanh: {tanh.round(2)}") print(f"tanh_exp: {tanh_exp.round(2)}\n")
4-1. 시그모이드, 쌍곡선 함수, relu의 시각화
시각화를 통해 확인해보면, 시그모이드 함수가 tanh에 비해 완만하게 그려진 것을 확인할 수 있다.
relu는 대표적인 활성화 함수 중 하나로, 0이하일 때는 0을, 0이상일 경우에만 본래의 값을 출력하는 함수이다.
x = np.linspace(-3, 3, 100) sigmoid = 1 / (1 + np.exp(-x)) tanh = np.tanh(x) relu = np.maximum(x, 0) fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(x, sigmoid, label=r"$y = \sigma(x)$", alpha=0.7) ax.plot(x, tanh, label=r"$y = tanh(x)$", alpha=0.7) ax.plot(x, relu, label=r"$y = relu(x)$", alpha=0.7) ax.tick_params(labelsize=20) ax.legend(fontsize=20)
5. 2차 함수
#Quadratic Functions a = np.random.randint(0, 10, (10, )) square1 = a*a square2 = a**2 square3 = np.square(a) print(f"a: \n{a}\n") print(f"a*a: \n {square1}") print(f"a**2: \n {square2}") print(f"np.square(a): \n {square3}")
6. Irrational function (무리 함수)
유리 함수와 반대로, 두 다항함수, 다항식의 비로 나타낼 수 없는 함수를 가리킨다.
대표적으로 제곱근, 세제곱근이 있다.#Irrational Functions a = np.random.randint(0, 10, (4, )) sqrt1 = a**(1/2) sqrt2 = np.sqrt(a) cbrt1 = a**(1/3) cbrt2 = np.cbrt(a) print(f"a: \n {a}\n") print(f"a**(1/2): \n {sqrt1.round(2)}") print(f"np.sqrt(a): \n {sqrt2.round(2)}\n") print(f"a**(1/3): \n {cbrt1.round(2)}") print(f"np.cbrt(a): \n {cbrt2.round(2)}")
7. 유리 함수
위의 무리 함수와 반대로, 유리식으로 정의되는 함수를 가리킨다.
간단한 내용이니, 더이상의 설명은 생략...ㅠ#Rational Functions a = np.random.uniform(0, 10, (4, )) recip1 = 1/a recip2 = a**(-1) recip3 = np.reciprocal(a) print(f"a: \n {a.round(2)}\n") print(f"1/a: \n {recip1.round(2)}") print(f"a**(-1): \n {recip2.round(2)}") print(f"np.reciprocal(a): \n {recip3.round(2)}")
#Rational Functions a = np.random.uniform(0, 10, (4, )) y1 = a**(-2) y2 = np.reciprocal(np.square(a)) z1 = a**(-1/2) z2 = np.reciprocal(np.sqrt(a)) print(f"a: \n {a.round(2)}\n") print(f"y1: \n {y1.round(2)}") print(f"y2: \n {y2.round(2)}\n") print(f"z1: \n {z1.round(2)}") print(f"z2: \n {z2.round(2)}")
8. 멱함수
멱함수는 거듭제곱의 지수를 고정하고, 밑을 변수로 하는 함수이다. [5]
정의 또한 위키 백과의 예시를 참조했다.#power funcions a = np.random.uniform(0, 5, (4, )) s1 = np.square(a).round(2) s2 = (a**2).round(2) s3 = np.power(a, 2).round(2) re1 = np.reciprocal(a).round(2) re2 = (a**(-1)).round(2) re3 = np.power(a, -1).round(2) print("square") print(f"{s1}\n{s2}\n{s3}\n") print("reciprocal") print(f"{re1}\n{re2}\n{re3}")
# power funcions x = np.random.uniform(0, 5, (4,)) y1 = 3 * x ** 3 - 2 * x ** 2 + x - 2 y2 = 3 * np.power(x, 3) - 2 * np.power(x, 2) + x - 2 print(f"y1: \n {y1.round(2)}") print(f"y2: \n {y2.round(2)}")
a = np.random.uniform(0, 5, (4, )) sqrt1 = np.sqrt(a).round(2) sqrt2 = (a**(1/2)).round(2) sqrt3 = np.power(a, (1/2)).round(2) cbrt1 = np.cbrt(a).round(2) cbrt2 = (a**(1/3)).round(2) cbrt3 = np.power(a, (1/3)).round(2) print("sqrt") print(f"{sqrt1}\n{sqrt2}\n{sqrt3}\n") print("cbrt") print(f"{cbrt1}\n{cbrt2}\n{cbrt3}")
지수 함수도 마찬가지로, 지수가 고정되면 멱함수의 일종이라고 볼 수 있다.
a = np.random.uniform(0, 5, (4, )) exp1 = np.exp(a).round(2) exp2 = (np.e**a).round(2) exp3 = np.power(np.e, a).round(2) print(f"{exp1}\n{exp2}\n{exp3}\n")
a = np.random.uniform(0, 5, (4, )) b = np.random.uniform(0, 5, (4, )) power1 = (a**b).round(2) power2 = np.power(a, b).round(2) print(f"{power1}\n{power2}")
9. 로그 함수
지수함수의 역함수이며, 어떤 수를 나타내기 위해 정해진 밑을 몇번 곱해야하는지를 나타낸다.
간단하게 3**4 = 81인데, 이를 로그로 표현하면
즉, 81을 표현하기 위해 3을 몇번 곱해야하는지를 표현할 수 있다. 답은 위의 지수 표현식을 볼 수 있듯이 4다.
이러한 로그를 이용해 다양한 확률론을 구할 수 있다고 하는데,
예를 들어 동전던지기를 무한하게 던질 때 특정한 면이 나올 확률이 1/2이라고 하면,
나오지 않을 확률은이렇게 표현할 수 있을 것이다.
# log functions x = np.linspace(0.001, 10, 300) log = np.log(x) fig, ax = plt.subplots(figsize=(20, 10)) ax.plot(x, log) ax.tick_params(labelsize=20)
# log functions a = np.random.uniform(1, 5, (4, )) log = np.log(a) exp = np.exp(log) print(f"a: \n {a.round(3)}") print(f"log: \n {log.round(3)}") print(f"exp: \n {exp.round(3)}")
#Properties of Log a = np.random.uniform(1, 5, (4, )) b = np.random.uniform(1, 5, (4, )) print((np.log(a) + np.log(b)).round(3)) print(np.log(a*b).round(3))
#Properties of Log a = np.random.uniform(1, 5, (4, )) log2 = np.log(a)/np.log(2) log3 = np.log(a)/np.log(3) log5 = np.log(a)/np.log(5) print(f"log2: \n {log2.round(3)}") print(f"log3: \n {log3.round(3)}") print(f"log5: \n {log5.round(3)}")
p = np.random.uniform(0, 1, (4, )) be_e = -(p*np.log(p) + (1-p)*np.log(1-p)) be_2 = -(p*np.log(p)/np.log(2) + (1-p)*np.log(1-p)/np.log(2)) print(f"probability: \n {p.round(2)}") print(f"binary entropy with base e: \n {be_e.round(2)}") print(f"binary entropy with base 2: \n {be_2.round(2)}")
[1] https://ko.wikipedia.org/wiki/%EB%9D%BC%EB%94%94%EC%95%88
라디안 - 위키백과, 우리 모두의 백과사전
라디안단위의 종류SI 유도 단위측정 대상각기호rad 또는 c 단위무한분량단위 환산 1 rad ▼동등 환산값 밀리라디안 1,000 밀리라디안 바퀴 1/2π 바퀴 도 180/π ≈ 57.296°
ko.wikipedia.org
[2] https://ko.wikipedia.org/wiki/%EB%B0%80%EB%A6%AC%EB%9D%BC%EB%94%94%EC%95%88
밀리라디안 - 위키백과, 우리 모두의 백과사전
밀리라디안(milliradian, 기호: mrad) 또는 밀(Mil)은 주로 군사관련으로 사용되는 각도(평면각)의 단위로, 1 밀리라디안은 1/1000 라디안이다. 밀이라는 명칭도 밀리(Milli)에서 유래한 것이다. 이 정의에
ko.wikipedia.org
[3] https://namu.wiki/w/%EC%8C%8D%EA%B3%A1%EC%84%A0%20%ED%95%A8%EC%88%98
[4] https://ko.wikipedia.org/wiki/%EC%8C%8D%EA%B3%A1%EC%84%A0_%ED%95%A8%EC%88%98
쌍곡선 함수 - 위키백과, 우리 모두의 백과사전
수학에서, 쌍곡선 함수(双曲線函數, 영어: hyperbolic function)는 일반적인 삼각함수와 유사한 성질을 갖는 함수로 삼각함수가 단위원 그래프를 매개변수로 표시할 때 나오는 것처럼, 표준쌍곡선을
ko.wikipedia.org
[5] https://ko.wikipedia.org/wiki/%EB%A9%B1%ED%95%A8%EC%88%98
멱함수 - 위키백과, 우리 모두의 백과사전
ko.wikipedia.org
'공부 > likelion' 카테고리의 다른 글
N. MSE , BCEE, CCEE의 Jacobians 구해보기(정리중) (0) 2021.10.22 10. rounding and sorting (0) 2021.10.17 9. Sum, Prod, Diff and Statistics (0) 2021.10.12 8. axis and keepdims Arguments (0) 2021.10.08 7. Indexing and Slicing ndarrays (0) 2021.10.06