Skip to content

Commit 6fae9f0

Browse files
nainsysgitbook-bot
authored andcommitted
GitBook: [master] 6 pages and 8 assets modified
1 parent 7f22091 commit 6fae9f0

13 files changed

+315
-1
lines changed

Diff for: .gitbook/assets/31501.png

49.4 KB
Loading

Diff for: .gitbook/assets/31521.png

21.9 KB
Loading

Diff for: .gitbook/assets/31522.png

64.1 KB
Loading

Diff for: .gitbook/assets/31531.png

49.9 KB
Loading

Diff for: .gitbook/assets/31532.png

31 KB
Loading

Diff for: .gitbook/assets/31533.png

69 KB
Loading

Diff for: .gitbook/assets/31534.png

449 KB
Loading

Diff for: .gitbook/assets/31535.png

895 KB
Loading

Diff for: 4.-numpy-and-scipy/4.3-scipy/4.3.1.-interpolation.md

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 4.3.1. Interpolation
2+
3+
보간법\(interpolation\)이란 표본데이터가 주어졌을 때 각 점들의 중간 값\(사이값\)을 구하면, 표본 데이터가 아닌 영역에서 데이터가 어떻게 될지 예상하는데 도움이 됩니다. 즉 discrete한 sample들을 바탕으로 우리가 가지고 있지 않는 점의 값을 추정하는 방법입니다.
4+
5+
사인\(sine\) 함수에 가까운 실험 데이터를 생각해 보겠습니다. 다음 예제는 NumPy, Matplotlib, SciPy를 종합적으로 사용합니다.
6+
7+
```python
8+
import numpy as np
9+
from scipy.interpolate import interp1d
10+
from matplotlib import pyplot as plt
11+
12+
# Cosine 함수를 0부터 10pi까지 20개 만든다.
13+
x = np.linspace(0,10*np.pi, 20)
14+
y = np.cos(x)
15+
16+
#interoperate 함수로 보간법을 적용하여 linear(선형보정) quadratic(부드러운 보정) 두가지 방법으로 만든다
17+
fl = interp1d(x,y,kind = 'linear')
18+
fq = interp1d(x,y,kind = 'quadratic')
19+
20+
xint = np.linspace(x.min(), x.max(), 1000)
21+
yintl = fl(xint)
22+
yintq = fq(xint)
23+
24+
# Plot the data and the interpolation
25+
plt.plot(xint, yintl, color = 'green', linewidth=2)
26+
plt.plot(xint, yintq, color = 'red', linewidth=2)
27+
plt.legend(['Linear','Quadratic'])
28+
plt.plot(x,y,'o') #값의 위치를 점으로 표현
29+
plt.ylim(-2,2)
30+
31+
plt.title('Interoperate')
32+
plt.show()
33+
```
34+
35+
위의 코드를 실행하면 다음과 같은 그래프가 출력 됩니다.
36+
37+
![](../../.gitbook/assets/31501.png)
38+

Diff for: 4.-numpy-and-scipy/4.3-scipy/4.3.2.-optimization.md

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# 4.3.2. Optimization
2+
3+
Optimization\(최적화\)는 최소화 또는 평형에 대한 수치 솔루션을 찾는 문제입니다. scipy.optimize 모듈은 함수 최소화 \(스칼라 또는 다차원\), 커브 피팅 및 루트 찾기를위 한 알고리즘을 제공합니다.
4+
5+
이 모듈의 함수들을 이해하려면 많은 수학적인 이론들이 필요합니다. 너무 어려워서 저도 대부분을 이해하지 못합니다. 사용법만 확인해 봅니다.
6+
7+
데이터를 수식\(함수\)로 만드는 과정을 Curve fitting 혹은 Data fitting이라고 합니다.
8+
9+
예제를 풀어보겠습니다. 1월부터 시작되는 매월 알래스카의 기온은 섭씨로 다음과 같습니다.
10+
11+
우리는 알래스카의 최소 및 최대 기온을 매달에 측정하여 매년 변화하는 것을 나타내는 함수를 찾으려고 합니다. 이를 위해 우리는 주기적 함수를 적용할 것입니다.
12+
13+
```text
14+
max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18
15+
min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58
16+
```
17+
18+
위의 데이터를 그래프로 표시하는 코드는 다음과 같습니다.
19+
20+
```python
21+
import numpy as np
22+
import matplotlib.pyplot as plt
23+
24+
temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])
25+
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])
26+
27+
months = np.arange(12)
28+
plt.plot(months, temp_max, 'ro')
29+
plt.plot(months, temp_min, 'bo')
30+
plt.xlabel('Month')
31+
plt.ylabel('Min and max temperature')
32+
33+
plt.show()
34+
```
35+
36+
위의 코드를 실행하면 다음과 같은 그래프가 나타납니다. 붉은 점은 최대온도, 파란 점은 최저 온도를 나타내는 것입니다.
37+
38+
![](../../.gitbook/assets/31521.png)
39+
40+
이 데이터에 주기적 함수를 적용해 보겠습니다.
41+
42+
curve\_fit 함수에 제공되는 인수는 다음과 같습니다.
43+
44+
* **f : 모델** **함수** f\(x, …\), 독립 변수를 첫 번째 인수로 사용하고 매개 변수를 별도의 나머지 인수로 사용해야 합니다.
45+
* **xdata :** k 예측자를 갖는 함수의 M 길이 시퀀스 또는 \(k, M\) 모양의 배열, 데이터가 측정되는 독립 변수입니다.
46+
* **ydata :** M- 길이 시퀀스, 종속 데이터 - 명목상 f \(xdata, ...\)
47+
* **p0 :** 없거나, 스칼라 또는 N 길이 시퀀스, 선택 사항입니다. 매개 변수에 대한 초기 추측 값. 없다면 초기 값은 모두 1이 됩니다.
48+
49+
여기서 커브 피팅에 대한 모델 함수를 구하는 방법은 상단히 복잡한 수학적 이론이 필요합니다. 여기서 함수의 사용법만 체크하고 넘어 갑니다.
50+
51+
위의 코드에 아래에 다음 코드를 추가해 보겠습니다.
52+
53+
```python
54+
from scipy import optimize
55+
def yearly_temps(times, avg, ampl, time_offset):
56+
return (avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()))
57+
58+
res_max, cov_max = optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0])
59+
res_min, cov_min = optimize.curve_fit(yearly_temps, months, temp_min, [-40,20,0])
60+
```
61+
62+
테스트를 위해 위의 코드 아래에 다음 코드를 추가해 봅니다
63+
64+
```python
65+
days = np.linspace(0, 12, num=365)
66+
67+
plt.figure()
68+
plt.plot(months, temp_max, 'ro')
69+
plt.plot(days, yearly_temps(days, *res_max), 'r-')
70+
plt.plot(months, temp_min, 'bo')
71+
plt.plot(days, yearly_temps(days, *res_min), 'b-')
72+
plt.xlabel('Month')
73+
plt.ylabel('Temperature ($^\circ$C)')
74+
plt.show()
75+
```
76+
77+
결과로 출력되는 두 플롯을 비교해 보십시요.
78+
79+
![](../../.gitbook/assets/31522.png)
80+
81+
전체 소스 코드는 다음과 같습니다.
82+
83+
```python
84+
import numpy as np
85+
import matplotlib.pyplot as plt
86+
87+
temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])
88+
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])
89+
90+
months = np.arange(12)
91+
plt.plot(months, temp_max, 'ro')
92+
plt.plot(months, temp_min, 'bo')
93+
plt.xlabel('Month')
94+
plt.ylabel('Min and max temperature')
95+
96+
97+
from scipy import optimize
98+
def yearly_temps(times, avg, ampl, time_offset):
99+
return (avg
100+
+ ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()))
101+
102+
res_max, cov_max = optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0])
103+
res_min, cov_min = optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0])
104+
105+
days = np.linspace(0, 12, num=365)
106+
107+
plt.figure()
108+
plt.plot(months, temp_max, 'ro')
109+
plt.plot(days, yearly_temps(days, *res_max), 'r-')
110+
plt.plot(months, temp_min, 'bo')
111+
plt.plot(days, yearly_temps(days, *res_min), 'b-')
112+
plt.xlabel('Month')
113+
plt.ylabel('Temperature ($^\circ$C)')
114+
115+
plt.show()
116+
```
117+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# 4.3.3. Fast Fourier transforms: scipy.fftpack
2+
3+
scipy.fftpack 모듈은 fast Fourier transforms \(FFT\)을 계산하고 이를 처리 할 수 있는 유틸리티를 제공합니다. 주요 기능은 다음과 같습니다.
4+
5+
* scipy.fftpack.fft \(\)를 사용하여 FFT를 계산
6+
* scipy.fftpack.fftfreq \(\)를 사용하여 샘플링 주파수 생성
7+
* scipy.fftpack.ifft \(\)는 주파수 공간에서 신호 공간으로 inverse FFT를 계산
8+
9+
다음 예제를 실습해 보겠습니다. 이 예제는 signal의 FFT의 힘을 플롯하고 inverse FFT를 사용하여 signal을 재구성하는 것입니다. 이 예제는 scipy.fftpack.fft\(\), scipy.fftpack.fftfreq\(\) 및 scipy.fftpack.ifft\(\)를 보여줍니다.
10+
11+
```python
12+
import numpy as np
13+
from scipy import fftpack
14+
from matplotlib import pyplot as plt
15+
16+
#신호를 생성합니다.
17+
# Seed the random number generator
18+
np.random.seed(1234)
19+
20+
time_step = 0.02
21+
period = 5.
22+
23+
time_vec = np.arange(0, 20, time_step)
24+
sig = (np.sin(2 * np.pi / period * time_vec) + 0.5 * np.random.randn(time_vec.size))
25+
26+
plt.figure(figsize=(6, 5))
27+
plt.plot(time_vec, sig, label='Original signal')
28+
29+
#FFT의 Power를 계산합니다.
30+
# The FFT of the signal
31+
sig_fft = fftpack.fft(sig)
32+
33+
# And the power (sig_fft is of complex dtype)
34+
power = np.abs(sig_fft)
35+
36+
# The corresponding frequencies
37+
sample_freq = fftpack.fftfreq(sig.size, d=time_step)
38+
39+
# Plot the FFT power
40+
plt.figure(figsize=(6, 5))
41+
plt.plot(sample_freq, power)
42+
plt.xlabel('Frequency [Hz]')
43+
plt.ylabel('plower')
44+
45+
# Find the peak frequency: we can focus on only the positive frequencies
46+
pos_mask = np.where(sample_freq > 0)
47+
freqs = sample_freq[pos_mask]
48+
peak_freq = freqs[power[pos_mask].argmax()]
49+
50+
# Check that it does indeed correspond to the frequency that we generate
51+
# the signal with
52+
np.allclose(peak_freq, 1./period)
53+
54+
# An inner plot to show the peak frequency
55+
axes = plt.axes([0.55, 0.3, 0.3, 0.5])
56+
plt.title('Peak frequency')
57+
plt.plot(freqs[:8], power[:8])
58+
plt.setp(axes, yticks=[])
59+
# scipy.signal.find_peaks_cwt can also be used for more advanced peak detection
60+
61+
62+
#모든 high frequencies를 제거합니다.
63+
high_freq_fft = sig_fft.copy()
64+
high_freq_fft[np.abs(sample_freq) > peak_freq] = 0
65+
filtered_sig = fftpack.ifft(high_freq_fft)
66+
67+
plt.figure(figsize=(6, 5))
68+
plt.plot(time_vec, sig, label='Original signal')
69+
plt.plot(time_vec, filtered_sig, linewidth=3, label='Filtered signal')
70+
plt.xlabel('Time [s]')
71+
plt.ylabel('Amplitude')
72+
73+
plt.legend(loc='best')
74+
75+
plt.show()
76+
```
77+
78+
위의 코드는 다음과 같은 그래프를 결과로 출력합니다. 먼저 아래 그래프는 signal을 생성한 후 original signal을 표시한 것입니다.
79+
80+
![](../../.gitbook/assets/31531.png)
81+
82+
이 original signal에 fft를 사용하여 power를 표시하면 다음과 같습니다.
83+
84+
![](../../.gitbook/assets/31532.png)
85+
86+
모든 high frequencies를 제거하면 다음과 같은 그래프를 얻을 수 있습니다.
87+
88+
![](../../.gitbook/assets/31533.png)
89+
90+
다음 예제를 실습해 보자. 포토샵 등에서 많이 사용하는 Gaussian image blur 효과를 사진에 적용하는 것입니다.
91+
92+
먼저 사진 이미지를 화면에 출력하는 코드를 실행 해 보겠습니다자.
93+
94+
```python
95+
import numpy as np
96+
from scipy import fftpack
97+
import matplotlib.pyplot as plt
98+
99+
# read image
100+
img = plt.imread('./IMG_0820.png')
101+
plt.figure()
102+
plt.imshow(img)
103+
104+
plt.show()
105+
```
106+
107+
IMG\_0820.png 는 대전 동학사의 벗꽃 사진입니다. 위의 코드를 실행하면 다음과 같은 이미지가 나타납니다. 굉장히 크고 해상도가 좋은 사진 원본입니다.
108+
109+
![](../../.gitbook/assets/31534.png)
110+
111+
이제 Gaussian convolution kernel 을 준비하고 FFT를 사용하여 적용해 봅니다.
112+
113+
전체 소스코드는 다음과 같습니다.
114+
115+
```python
116+
import numpy as np
117+
from scipy import fftpack
118+
import matplotlib.pyplot as plt
119+
120+
# read image
121+
img = plt.imread('./IMG_0820.png')
122+
plt.figure()
123+
plt.imshow(img)
124+
125+
# First a 1-D Gaussian
126+
t = np.linspace(-10, 10, 30)
127+
bump = np.exp(-0.1*t**2)
128+
bump /= np.trapz(bump) # normalize the integral to 1
129+
130+
# make a 2-D kernel out of it
131+
kernel = bump[:, np.newaxis] * bump[np.newaxis, :]
132+
133+
# Padded fourier transform, with the same shape as the image
134+
# We use :func:`scipy.signal.fftpack.fft2` to have a 2D FFT
135+
kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1))
136+
137+
# convolve
138+
img_ft = fftpack.fft2(img, axes=(0, 1))
139+
# the 'newaxis' is to match to color direction
140+
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
141+
img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real
142+
143+
# clip values to range
144+
img2 = np.clip(img2, 0, 1)
145+
146+
# plot output
147+
plt.figure()
148+
plt.imshow(img2)
149+
150+
plt.show()
151+
```
152+
153+
출력되는 두개의 이미지를 비교해 보십시요….
154+
155+
![](../../.gitbook/assets/31535.png)
156+
File renamed without changes.

Diff for: SUMMARY.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,10 @@
9595
* [4.1.2. Indexing, Slicing 그리고 Iterating](4.-numpy-and-scipy/4.1-numpy/4.1.2.-indexing-slicing-iterating.md)
9696
* [3.13.3. Shape Manipulation](4.-numpy-and-scipy/4.1-numpy/3.13.3.-shape-manipulation.md)
9797
* [4.2 Matplotlib](4.-numpy-and-scipy/4.2-matplotlib.md)
98-
* [4.3 SciPy](4.-numpy-and-scipy/4.3-scipy.md)
98+
* [4.3 SciPy](4.-numpy-and-scipy/4.3-scipy/README.md)
99+
* [4.3.1. Interpolation](4.-numpy-and-scipy/4.3-scipy/4.3.1.-interpolation.md)
100+
* [4.3.2. Optimization](4.-numpy-and-scipy/4.3-scipy/4.3.2.-optimization.md)
101+
* [4.3.3. Fast Fourier transforms: scipy.fftpack](4.-numpy-and-scipy/4.3-scipy/4.3.3.-fast-fourier-transforms-scipy.fftpack.md)
99102
* [4.4 Pandas](4.-numpy-and-scipy/4.4-pandas.md)
100103
* [5. 머신러닝 & 딥러닝](4.-and.md)
101104
* [6. 간단한 챗봇 만들기](5..md)

0 commit comments

Comments
 (0)