1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
 
import numpy as np
 
 
# lambda 함수
 
f1 = lambda x: x+100
 
print(f1(10))  # 110
 
 
def test_lambda(a, b):
    print(a, b)
 
 
= 100
= 200
 
f2 = lambda x, y: test_lambda(a, b)
f3 = lambda x, y: test_lambda(x, y)
 
f2(12)  # 100 200
f3(12)  # 1 2
 
 
 
# list comprehension
 
data = [[15], [29], [317], [421]]
x_data = [x[0for x in data]
y_data = [x[1for x in data]
 
print(x_data)  #[1, 2, 3, 4]
print(y_data)  #[5, 9, 17, 21]
 
 
# with 구문 => with 블록을 벗어나는 순간 자동으로 close
 
with open("./test_file"'w'as f:
    f.write("good morning")
 
 
# iterator
data = np.array([[15], [29], [317], [421]])
 
it = np.nditer(data, flags=['multi_index'], op_flags=['readwrite'])
 
while not it.finished:
 
    idx = it.multi_index
    print(data[idx], end=" ")  # 1 5 2 9 3 17 4 21
 
    it.iternext()
 
print()
 
 
# numpy 행렬에 row or column 추가
 
matrix = np.array([[12], [34]])
 
print(matrix[:, -1].shape)  # (2,)
print(matrix[:, [-1]].shape)  # (2, 1)
 
add_row = np.array([56]).reshape(12)
matrix = np.concatenate((matrix, add_row), axis=0)
print(matrix)
 
add_column = np.array([102030]).reshape(31)
matrix = np.concatenate((matrix, add_column), axis=1)
print(matrix)
 
 
# 머신러닝 모델 구현 시, numpy 유틸리티 함수
data = np.array([1234])
 
print(np.sum(data))
print(np.exp(data))
print(np.log(data))
print(np.max(data))
print(np.min(data))
print(np.argmax(data))  # 3
print(np.argmin(data))   # 0
 
 
# 수치미분 구현 (1)
 
def test_func(x):
    return x**2
 
 
def numerical_derivative(func, x):
    delta = 1e-4
 
    return (func(x+delta)-func(x-delta))/(2*delta)
 
 
print(numerical_derivative(test_func, 5))  # 9.9999 == 10
 
 
# 수치미분 구현 (2)
 
def test_func2(x):
 
    v1 = x[0]
    v2 = x[1]
 
    return v1**2 + v2*3
 
 
def numerical_derivative_2(func, x):
 
    delta = 1e-4
    grad = np.zeros_like(x)
 
    it2= np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
 
    while not it2.finished:
        idx = it2.multi_index
 
        temp = x[idx]
        x[idx] = float(temp) + delta
        f1 = func(x)
 
        x[idx] = float(temp) - delta
        f2 = func(x)
 
        grad[idx] = (f1-f2)/(2*delta)
 
        x[idx] = temp
        it2.iternext()
 
    return grad
 
 
 
print(numerical_derivative_2(test_func2, np.array([2.03.0])))  # [4. 3.]
cs

 

 

반응형

'머신러닝_딥러닝 > Tensorflow + Keras' 카테고리의 다른 글

XOR 문제 (딥러닝으로 해결)  (0) 2021.10.23
XOR 문제  (0) 2021.10.23
로지스틱 회귀 (Logistic Regression)  (0) 2021.10.23
선형회귀 (Linear Regression)  (0) 2021.10.23
Tensorflow & Keras  (0) 2021.09.14

+ Recent posts