Coding 공부/Big data & Python

[Big data & Python] 딥러닝, 넘파이(numpy), 텐서플로우 케라스 예제(Tensorflow.kreras), 파이토치 예제(totch)

CBJH 2024. 5. 11. 16:07
728x90
반응형

1. 딥러닝 이론

딥러닝 이론 : https://just-record.github.io/deep-learning/deeplearning-overview/

딥러닝 학습과정 시각화 실습 링크 : https://playground.tensorflow.org/

 

2. 넘파이(numpy)

링크 : https://just-record.github.io/python-data_analysis/python-numpy-01/

 

2.1 넘파이 예제

# pip install numpy
import numpy as np

# 가상의 데이터 생성: y = 2x + 1 + 잡음
np.random.seed(0)
x = np.random.rand(100, 1)  # 100개의 x 값
y = 2 * x + 1 + 0.1 * np.random.randn(100, 1)  # y 값에 약간의 잡음 추가, 데이터를 외부에서 얻었다는 가정. 외부에서 얻은 데이터 y.


# 모델의 매개변수 초기화
w = np.random.randn(1)      #w : 가중치
b = np.random.randn(1)      #b : 편향치
print("w: ", w)
print("b: ", b)


# 학습률과 반복 횟수 설정
learning_rate = 0.1     #0.1만큼 이동해라
iterations = 300        #300번 수행해라

# 손실 함수: 평균 제곱 오차(MSE)
def loss_function(x, y, w, b):
    predictions = w * x + b         #predictions : 모델(랜덤한 가중치, 편향치를 넣은)에 대한 예상치
    loss = np.mean((y - predictions) ** 2)
    return loss

# 경사 하강법
for i in range(iterations):         #iterations 크기(300)만큼 테스트를 돌려보겠다.
    predictions = w * x + b         #x가 100개 이므로 predictions도 100개 생성
    loss = loss_function(x, y, w, b)    #loss도 100개 생성
    
    # 손실에 대한 w, b의 그래디언트 계산
    w_grad = -2 * np.mean((y - predictions) * x)        #가중치 미분 한 값(손실률 함수를 가중치에 대해 미분한 값) : 기울기
    b_grad = -2 * np.mean(y - predictions)              #편향치 미분 한 값(손실률 함수를 편향치에 대해 미분한 값) : 기울기
    
    # 매개변수 업데이트
    w -= learning_rate * w_grad            
    b -= learning_rate * b_grad
    
    print(f"Iteration {i+1}: w = {w[0]}, b = {b[0]}, Loss = {loss}")

# 최종 모델 출력
print(f"Final model: y = {w[0]}x + {b[0]}")

new_x = np.random.rand(5, 1)  # 5개의 새로운 x 값
actual_y = 2 * new_x + 1  # 실제 2x + 1 값 계산
new_predictions = w[0] * new_x + b[0]

print("New input x values:", new_x)
print("Actual y values (2x + 1):", actual_y)
print("Predicted y values:", new_predictions)

 

 

3. 텐서플로우 케라스 예제(Tensorflow.kreras)

# pip install tensorflow

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD

# 가상의 데이터 생성 (y = 2x + 1)
np.random.seed(0)
x = np.random.rand(100, 1)  # 100개의 x 값
y = 2 * x + 1 + 0.1 * np.random.randn(100, 1)  # y 값에 약간의 잡음 추가

# 모델 구성
model = Sequential()
model.add(Dense(1, input_dim=1, activation='linear'))  # 1차원, 선형구조. 선형 회귀이므로 활성화 함수는 선형(기본값)

# 모델 컴파일: 손실 함수 및 최적화 방법 설정
model.compile(optimizer=SGD(learning_rate=0.1), loss='mse')         #SGD : 확률적 경사하강법을 사용하겠다. leaning_rate : 학습 이동 범위 설정, loss 손실률 mse : meansqured error 에러를 루트씌움

# 모델 학습
model.fit(x, y, epochs=100)     #epochs : ~번 돌리겠다.


# 최종 모델의 가중치와 편향 출력
weights, bias = model.layers[0].get_weights()
print(f"Learned weight: {weights[0][0]}, Learned bias: {bias[0]}")


# 새로운 데이터 5개 생성
new_x = np.random.rand(5, 1)  # 5개의 새로운 x 값
new_y_actual = 2 * new_x + 1  # 새로운 데이터에 대한 실제 y 값 계산

# 새로운 데이터에 대한 예측 수행
new_predictions = model.predict(new_x)          #predict() : 매개변수에 대한 예상값을 출력하는 메서드

# 출력
print("New input x values:", new_x.flatten())  # 새로운 입력값 출력
print("Actual y values:", new_y_actual.flatten())  # 새로운 입력에 대한 실제 y 값 출력
print("Predicted y values:", new_predictions.flatten())  # 예측된 y 값 출력

 

 

4. 파이토치 예제(totch)

# pip install torch torchvision torchaudio # windows, cpu 기준

import torch
import torch.nn as nn
import torch.optim as optim

# 데이터 생성
torch.manual_seed(0)
x = torch.rand(100, 1)  # 100개의 x 값
y = 2 * x + 1 + 0.1 * torch.randn(100, 1)  # y 값에 약간의 잡음 추가

# 모델 정의, 선형 모델을 직접 만들어줘야한다. 텐서플로우 케라스에서는 기본적인 모델은 이미 만들어져 있어서 불러오기만 하면 된다. 차이점.
class LinearRegressionModel(nn.Module):
    def __init__(self):
        super(LinearRegressionModel, self).__init__()
        self.linear = nn.Linear(1, 1)  # 입력 차원 1, 출력 차원 1

    def forward(self, x):
        return self.linear(x)

# 모델 인스턴스 생성
model = LinearRegressionModel()

# 손실 함수 및 최적화기 정의
criterion = nn.MSELoss()                            #손실 함수로 criterion을 사용하겠다.
optimizer = optim.SGD(model.parameters(), lr=0.1)   #optim.SGD : 확률적 경사 모듈을 사용하겠다. lr : Learing rate 0.1단위로 학습시키겠다.

# 모델 훈련
epochs = 300                #300번 돌리겠다.
for epoch in range(epochs):
    model.train()
    optimizer.zero_grad()  # 기울기 초기화, 기울기 0으로
    outputs = model(x)
    loss = criterion(outputs, y)    #매개변수 : 모델 예측값 ouputs, 실제 값 y, loss: 손실값
    loss.backward()  # 역전파 실행, 결과값을 받아 미분해주겠다. 거꾸로 실행.
    optimizer.step()  # 매개변수 업데이트
    
    print(f"Epoch {epoch+1}/{epochs}, Loss: {loss.item()}")

# 최종 모델의 가중치와 편향 출력
final_weights = model.linear.weight.data
final_bias = model.linear.bias.data
print(f"Learned weight: {final_weights.item()}, Learned bias: {final_bias.item()}")

# 새로운 입력 데이터 생성 (예측을 위해)
new_x = torch.rand(5, 1)  # 5개의 새로운 x 값
actual_y = 2 * new_x + 1  # 실제 2x + 1 값 계산
model.eval()  # 모델을 평가 모드로 설정
with torch.no_grad():  # 그래디언트 계산 비활성화
    new_predictions = model(new_x)

# 예측 결과 출력
print("New input x values:", new_x.numpy())
print("Actual y values (2x + 1):", actual_y.numpy())
print("Predicted y values:", new_predictions.numpy())