2022.6.2 neural networks

정성우·2022년 6월 2일
0

학습한 내용

"""
단층 퍼셉트론 이용한 and nand or 게이트 구현

1.and
-두개의 입력값이 모두1인 경우만 1
"""

def And_gate(x1,x2):
    w1=0.5
    w2=0.5
    b=-0.7

    result=x1*w1+x2*w2+b

    if result <=0:
        return 0
    else:
        return 1
test1 =And_gate(1,1)
test2 =And_gate(1,0)
test3 =And_gate(0,1)
test4 =And_gate(0,0)
print("test>>",test1,test2,test3,test4)


"""
nand 게이트 : 두개의 입력값이 1인 경우에만 출력값이 0
"""

def NAnd_gate(x1,x2):
    w1=0.5
    w2=0.5
    b=-0.7

    result=x1*w1+x2*w2+b

    if result <=0:
        return 1
    else:
        return 0
test1 =NAnd_gate(1,1)
test2 =NAnd_gate(1,0)
test3 =NAnd_gate(0,1)
test4 =NAnd_gate(0,0)
print("test>>",test1,test2,test3,test4)

"""
or 게이트 : 두개의 입력값이 0인 경우에만 출력값이 0
"""

def or_gate(x1,x2):
    w1=0.1
    w2=0.1
    b=-0.1

    result=x1*w1+x2*w2+b

    if result >=0:
        return 1
    else:
        return 0
test1 =or_gate(1,1)
test2 =or_gate(1,0)
test3 =or_gate(0,1)
test4 =or_gate(0,0)
print("test>>",test1,test2,test3,test4)

실행결과

학습한 내용

"""
파이토치로 다층 퍼셉트론 구현하기 
"""
import torch
import torch.nn as nn
"""
# GPU 사용가능한 여부 파악 test code -> CPU 인텔 엔비디아 GPU / AMD 엔비디아 GPU 맥북 M1 
device = "cuda" if torch.cuda.is_available() else "cpu"
"""

# M1 사용중인 분들
device = torch.device("cpu")
# str_device = str(device)
# print("device info >> ", type(str_device))

# seed
torch.manual_seed(777)

if device == "cpu":
    torch.cuda.manual_seed_all(777)

# 데이터 생성
x = [[0, 0], [0, 1], [1, 0], [1, 1]]
y = [[0], [1], [1], [0]]

# 데이터 텐서 변경
x = torch.tensor(x, dtype=torch.float32).to(device)
y = torch.tensor(y, dtype=torch.float32).to(device)

print("x", x)
print("y", y)

model = nn.Sequential(
    nn.Linear(2,10,bias=True),
    nn.Sigmoid(),
    nn.Linear(10,10,bias=True),
    nn.Sigmoid(),
    nn.Linear(10,10,bias=True),
    nn.Sigmoid(),
    nn.Linear(10,1,bias=True),
    nn.Sigmoid(),
)

model.to(device)
print(model)


"""
Loss function BCELoss()
"""

criterion=torch.nn.BCELoss().to(device)
optimizer=torch.optim.SGD(model.parameters(),lr=0.01)

"""
학습코드 작성
"""
for epoch in range(10001):
    optimizer.zero_grad()
    output=model(x)

    loss=criterion(output,y)
    loss.backward()
    optimizer.step()

    if epoch%100==0:
        print(f"epoch>>{epoch} loss>>{loss.item()}")

with torch.no_grad():
    output=model(x)
    predicted=(output>0.5).float()
    acc=(predicted==y).float().mean()
    print("모델의 출력값 output",output.detach().cpu().numpy())
    print("모델의예측값predicted",predicted.detach().cpu().numpy())
    print("실제값",y.cpu().numpy())
    print("정확도>>>",acc.item()*100)

실행결과

"""
다층퍼셉트론으로 손글씨 분류 
사이킷런 패키지에서 제공하는 분류용 예측 데이터를 이용
0 ~ 9 까지의 숫자를 손으로 쓴 이미지 데이터로 load_digits() 명령어로 로드 
각 이미지 사이즈는 8 x 8  = 64px 구성 흑백이미지 이미지 갯수 1,797개 
"""
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits

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

digits = load_digits()
print("image 행렬 \n", digits.images[0])
print("타겟 >> ", digits.target[0])
print("전체 데이터 >> ", len(digits.images))

"""
상위 5개만 샘플이미지 확인 
zip 
image = [1,2,3,4]
label = [사과, 자몽 ,바나나, 수박]

list(zip(image, label))

1 사과 2 자몽 3 비나나 4 수박 
"""
# images_and_labels = list(zip(digits.images, digits.target))

# for index, (image, label) in enumerate(images_and_labels[:6]):
#     print(index)
#     plt.subplot(2, 5, index+1)
#     plt.axis('off')
#     plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
#     plt.title("smaple : % i" % label)
#     plt.show()


"데이터 생성 "
x = digits.data
y = digits.target

"모델 생성"

model = nn.Sequential(
    nn.Linear(64, 32),
    nn.ReLU(),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Linear(16, 10)
)

device = "cuda" if torch.cuda.is_available() else "cpu"

"데이터 텐서"
x = torch.tensor(x, dtype=torch.float32).to(device)
y = torch.tensor(y, dtype=torch.int64).to(device)

print(x, y)

loss_fn = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())

loss_list = []
for epoch in range(101):
    optimizer.zero_grad()
    output = model(x)
    loss = loss_fn(output, y)
    loss.backward()
    optimizer.step()

    if epoch % 10 == 0:
        print("epoch {:4d}/{} loss : {:.6f}".format(epoch, 100, loss.item()))

    loss_list.append(loss.item())


plt.title("loss")
plt.plot(loss_list)
plt.show()

실행결과

학습한 내용 중 어려웠던 점 또는 해결못한 것들
모델링 하는부분이 어렵다

해결방법 작성

학습 소감
cnn 만들어봐서 재미있었다.

0개의 댓글