즐거운프로그래밍

[딥러닝] 딥러닝 인공 신경망 텐서플로(tensorflow)로 구현하기 연습문제

수수께끼 고양이 2023. 10. 28. 21:42
728x90
반응형

 

연습문제 1. 텐서플로를 사용하여 2입력 1출력 인공 신경망 구현하기

import tensorflow as tf
import numpy as np

X=np.array([[2,3]]) # 입력데이터
YT=np.array([[27]]) # 목표데이터(라벨)
W=np.array([[3],[4]]) # 가중치
B=np.array([1]) # 편향

model=tf.keras.Sequential([ 
    tf.keras.Input(shape=(2,)), # 입력층 노드의 개수를 1로 설정합니다.
    tf.keras.layers.Dense(1) # 출력층 노드의 개수를 1로 설정합니다.
]) # 신경망 모양 결정(W,B 내부적 준비)

model.layers[0].set_weights([W,B])

model.compile(optimizer='sgd', # 7공식, 학습 / 자바의 컴파일이 아님
              loss='mse') # 2공식, 오차 계산(E)

Y=model.predict(X)
print(Y)

model.fit(X,YT,epochs=999,verbose=0)

print('W=',model.layers[0].get_weights()[0])
print('B=',model.layers[0].get_weights()[1])

Y=model.predict(X)
print(Y)

 

 

 


연습문제 2. 2입력 2출력 인공신경망 구현하기

import tensorflow as tf
import numpy as np

X=np.array([[2,3]]) # 입력데이터
YT=np.array([[27,-30]]) # 목표데이터(라벨)
W=np.array([[3,5],[4,6]]) # 가중치
B=np.array([1,2]) # 편향

model=tf.keras.Sequential([ 
    tf.keras.Input(shape=(2,)), # 입력층 노드의 개수를 1로 설정합니다.
    tf.keras.layers.Dense(2) # 출력층 노드의 개수를 1로 설정합니다.
]) # 신경망 모양 결정(W,B 내부적 준비)

model.layers[0].set_weights([W,B])

model.compile(optimizer='sgd', # 7공식, 학습 / 자바의 컴파일이 아님
              loss='mse') # 2공식, 오차 계산(E)

Y=model.predict(X)
print(Y)

model.fit(X,YT,epochs=999,verbose=0)

print('W=',model.layers[0].get_weights()[0])
print('B=',model.layers[0].get_weights()[1])

Y=model.predict(X)
print(Y)

 

 

 


연습문제 3. 2입력 2은닉 2출력 인공신경망 구현하기

import tensorflow as tf
import numpy as np

X=np.array([[.05,.10]]) # 입력데이터 <=
YT=np.array([[.01,.99]]) # 목표데이터(라벨)
W=np.array([[.15,.25],[.20,.30]]) # 가중치 <=
B=np.array([.35,.35]) # 편향
W2=np.array([[.40,.50],[.45,.55]]) # 가중치 <=
B2=np.array([.60,.60]) # 편향

model=tf.keras.Sequential([ 
    tf.keras.Input(shape=(2,)), # 입력층 노드의 개수를 1로 설정합니다.
    tf.keras.layers.Dense(2), # 출력층 노드의 개수를 1로 설정합니다.
    tf.keras.layers.Dense(2)
]) # 신경망 모양 결정(W,B 내부적 준비)

model.layers[0].set_weights([W,B])
model.layers[1].set_weights([W2,B2])

model.compile(optimizer='sgd', # 7공식, 학습 / 자바의 컴파일이 아님
              loss='mse') # 2공식, 오차 계산(E)

Y=model.predict(X)
print(Y)

model.fit(X,YT,epochs=999,verbose=0)

print('W=',model.layers[0].get_weights()[0])
print('B=',model.layers[0].get_weights()[1])
print('W2=',model.layers[1].get_weights()[0])
print('B2=',model.layers[1].get_weights()[1])

Y=model.predict(X)
print(Y)

 

 

 

 

728x90
반응형