본문 바로가기

AI_딥_러닝_언어지능

AI_파이썬_언어지능_dll_binaryclassification2

import torch

# 학습할 데이터 (입력 값과 정답)
x_train = torch.FloatTensor([[1,1], [2,2], [3,3],[4,4],[5,3],[6,2],[8,1]])      
y_train = torch.FloatTensor([[0], [0], [0],[1],[1],[1],[0]])

# 가중치와 바이어스를 랜덤으로 생성
w = torch.randn([2,1], requires_grad=True)  # 가중치
b = torch.randn([1], requires_grad=True)    # 바이어스

# 경사 하강법으로 가중치와 바이어스를 업데이트할 방법을 지정
optimizer = torch.optim.SGD([w, b], lr=0.01)

# 모델 함수: x 값에 대해 예측 값을 계산
def H(x):
  # 행렬 곱셈 후 시그모이드 함수 적용하여 예측 값 반환
  model = torch.sigmoid(torch.matmul(x, w) + b)
  return model

# 학습 과정 (2000번 반복)
for iter in range(2000):
  # 이진 분류 손실 함수 계산
  cost = torch.mean((-1)*y_train*torch.log(H(x_train)) + (-1)*(1-y_train)*torch.log(1-H(x_train)))
  
  optimizer.zero_grad()  # 기울기를 0으로 초기화
  cost.backward()  # 기울기 계산
  optimizer.step()  # 가중치와 바이어스를 업데이트

  # 100번마다 손실 값 출력
  if iter % 100 == 0:
    print(iter, cost.detach().item())

# 모델로 예측하기
model_result = H(x_train)  # 학습 데이터로 예측
print("예측 결과:", model_result)

# 예측 결과를 0 또는 1로 변환 (임계값: 0.5)
model_result_1 = (model_result > 0.5).float()
print("변환된 예측 결과:", model_result_1)

 

0 3.0827579498291016
100 0.6619202494621277
200 0.6455783843994141
300 0.6337909698486328
400 0.623870849609375
500 0.6149017214775085
600 0.6065202355384827
700 0.5985772013664246
800 0.5910058617591858
900 0.5837698578834534
1000 0.5768455266952515
1100 0.5702139735221863
1200 0.5638583898544312
1300 0.557763934135437
1400 0.5519163012504578
1500 0.5463024973869324
1600 0.5409098267555237
1700 0.5357264876365662
1800 0.5307415723800659
1900 0.5259446501731873
tensor([[0.2479],
        [0.3966],
        [0.5672],
        [0.7233],
        [0.6173],
        [0.4989],
        [0.4054]], grad_fn=<SigmoidBackward0>)