-
AI Linear regression 예제인공지능 2020. 5. 24. 17:35728x90
개념 내용은 이전 글 참조바랍니당
2020/05/24 - [AI] - AI Linear regression 파이썬 구현
입력 데이터
import numpy as np try: load_data = np.loadtxt('./sps.csv', delimiter=',', dtype=np.float32) y_data = load_data[:, [0]] x_data = load_data[:, 1:] W = np.random.rand(4, 1) b = np.random.rand(1) def loss_func(x, t): y = np.dot(x, W) + b return (np.sum((t - y) ** 2)) / len(x) def predict(x): return np.dot(x, W) + b def numerical_derivative(f, input_data): delta_x = 1e-4 ret = np.zeros_like(input_data) it = np.nditer(input_data, flags=['multi_index'], op_flags=['readwrite']) while not it.finished: idx = it.multi_index tmp = input_data[idx] input_data[idx] = float(tmp) - delta_x fx1 = f(input_data) input_data[idx] = float(tmp) + delta_x fx2 = f(input_data) ret[idx] = (fx2 - fx1) / (2 * delta_x) input_data[idx] = tmp it.iternext() return ret learning_rate = 1e-4 f = lambda x: loss_func(x_data, y_data) print('Initial loss = ', loss_func(x_data, y_data), 'W = ', W, 'b = ', b) for step in range(8001): W -= learning_rate * numerical_derivative(f, W) b -= learning_rate * numerical_derivative(f, b) if step % 400 == 0: print('loss = ', loss_func(x_data, y_data), 'W = ', W, 'b = ', b) print(predict([2, -3, 9, 0])) except Exception as err: print(str(err))
결과
'인공지능' 카테고리의 다른 글
AI Logistic regression 예제 (0) 2020.05.26 AI Logistic regression : 분류(Classification) (0) 2020.05.24 AI Linear regression 파이썬 구현 (0) 2020.05.24 AI Gradient descent 알고리즘 (0) 2020.05.24 AI Linear Regression (0) 2020.05.24