728x90
SMALL
XX = [[100, 5]]
xx = torch.FloatTensor(XX);
hypothesis = torch.sigmoid(xx.matmul(W) + b)
prediction = hypothesis >= torch.FloatTensor([0.5])
print(prediction)
logistic regression과 linear regression의 가장큰 차이=logistic regression은 범주형 데이터를 다룸
로지스틱 회귀의 목적은 일반적인 회귀 분석의 목표와 동일하게 종속 변수와 독립 변수간의 관계를 구체적인 함수로 나타내어 향후 예측 모델에 사용하는 것이다. 이는 독립 변수의 선형 결합으로 종속 변수를 설명한다는 관점에서는 선형 회귀 분석과 유사하다. 하지만 로지스틱 회귀는 선형 회귀 분석과는 다르게 종속 변수가 범주형 데이터를 대상으로 하며 입력 데이터가 주어졌을 때 해당 데이터의 결과가 특정 분류로 나뉘기 때문에 일종의 분류 (classification) 기법으로도 볼 수 있다.
로시스틱 회귀문제-> 이진분류 혹은 여러클래스의 분류
<실습1>
데이터 로드
# pytorch
import torch
# 최적화 알고리즘 : SGD
import torch.optim as optim
# For reproducibility
torch.manual_seed(1)
# 임의 데이터 생성
x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]
y_data = [[0], [0], [0], [1], [1], [1]]
x_train = torch.FloatTensor(x_data)
y_train = torch.FloatTensor(y_data)
print(x_data)
print(x_train)
print(x_train.shape)
print(y_train.shape)
모델 학습
# 모델 초기화
# 입력데이터 (x) ==> 2
# 출력 (Y) ==> 0 / 1
W = torch.zeros((2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# optimizer 설정
optimizer = optim.SGD([W, b], lr=1) #lr=1은 알파가 1이라는 의미
nb_epochs = 1000
for epoch in range(nb_epochs + 1):
# Cost 계산
hypothesis = torch.sigmoid(x_train.matmul(W) + b) # or .mm or @
cost = -(y_train * torch.log(hypothesis) +
(1 - y_train) * torch.log(1 - hypothesis)).mean()
# cost로 H(x) 개선
optimizer.zero_grad()
cost.backward()
optimizer.step()
# 100번마다 로그 출력
if epoch % 100 == 0:
print('Epoch {:4d}/{} Cost: {:.6f}'.format(
epoch, nb_epochs, cost.item()
))
데이터 평가
hypothesis = torch.sigmoid(x_train.matmul(W) + b)
#print(hypothesis[:5]) 0과 1로 표현되어있지 않음
prediction = hypothesis >= torch.FloatTensor([0.5])
#print(prediction[:5]) 0.5를 기준으로 재레이블링
#print(prediction[:5])
#print(y_train[:5])
correct_prediction = prediction.float() == y_train
print(correct_prediction[:5])
accuracy = correct_prediction.sum().item() / len(correct_prediction)
print('The model has an accuracy of {:2.2f}% for the training set.'.format(accuracy * 100))
예측해보기
XX = [[100, 5]]
xx = torch.FloatTensor(XX);
hypothesis = torch.sigmoid(xx.matmul(W) + b)
prediction = hypothesis >= torch.FloatTensor([0.5])
print(prediction)
<2번-multi class>
Softmax classification
- 클래스가 3개 이상인 경우
데이터 로드
import torch
import torch.optim as optim
# For reproducibility
torch.manual_seed(1)
x_train = [[1, 2, 1, 1],
[2, 1, 3, 2],
[3, 1, 3, 4],
[4, 1, 5, 5],
[1, 7, 5, 5],
[1, 2, 5, 6],
[1, 6, 6, 6],
[1, 7, 7, 7]]
y_train = [2, 2, 2, 1, 1, 1, 0, 0]
x_train = torch.FloatTensor(x_train)
y_train = torch.LongTensor(y_train)
print(x_train[:5]) # 첫 다섯 개
print(y_train[:5])
print(y_train)
print(y_train.unsqueeze(1))
nb_class = 3
nb_data = len(y_train)
y_one_hot = torch.zeros(nb_data, nb_class)
y_one_hot.scatter_(1, y_train.unsqueeze(1), 1)
print(y_one_hot)
unsqueeze하는 것은 하나의 리스트에 있던걸 각각의 리스트로..
[2,2,2,1,1,1,0,0]->[[2],[2],[2],[1],[1],[1],[0],[0]]-->(one hot encoding)[[0 0 1],[0 0 1]......]
모델 학습
import torch.nn.functional as F # for softmax
# 모델 초기화
# feature 4개, 3개의 클래스
nb_class = 3
nb_data = len(y_train)
W = torch.zeros((4, nb_class), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# optimizer 설정
optimizer = optim.SGD([W, b], lr=0.01)
nb_epochs = 1000
for epoch in range(nb_epochs + 1):
# Cost 계산 (1)
hypothesis = F.softmax(x_train.matmul(W) + b, dim=1) # or .mm or @
# cost 표현번 1번 예시
y_one_hot = torch.zeros(nb_data, nb_class)
y_one_hot.scatter_(1, y_train.unsqueeze(1), 1)
cost = (y_one_hot * -torch.log(F.softmax(hypothesis, dim=1))).sum(dim=1).mean()
# cost 표현법 2번 예시
# cross_entropy를 사용하면 scatter 함수를 이용한 one_hot_encoding을 안해도 됨
# cost = F.cross_entropy((x_train.matmul(W) + b), y_train)
# cost로 H(x) 개선
optimizer.zero_grad()
cost.backward()
optimizer.step()
# 100번마다 로그 출력
if epoch % 100 == 0:
print('Epoch {:4d}/{} Cost: {:.6f}'.format(
epoch, nb_epochs, cost.item()
))
데이터 평가
# 학습된 W,b를 통한 클래스 예측
hypothesis = F.softmax(x_train.matmul(W) + b, dim=1) # or .mm or @
predict = torch.argmax(hypothesis, dim=1)
torch.argmax()
print(hypothesis)
print(predict)
print(y_train)
# 정확도 계산
correct_prediction = predict.float() == y_train
print(correct_prediction)
accuracy = correct_prediction.sum().item() / len(correct_prediction)
print('The model has an accuracy of {:2.2f}% for the training set.'.format(accuracy * 100))
argmax=> 가장 큰 값의 인덱스를 return
728x90
LIST
'AI' 카테고리의 다른 글
실습- MINST (0) | 2022.10.03 |
---|---|
다중 퍼셉트론(이론) (0) | 2022.10.03 |
선형분류(Linear Classification) 이론 (0) | 2022.10.02 |
선형회귀_실습 (0) | 2022.09.30 |
선형 회귀(Linear Regression) (0) | 2022.09.30 |