즐거운프로그래밍

[딥러닝] 딥러닝 목표값 변경, 은닉층 늘리기, 학습 후 모델 내보내기, 모델 불러와 예측하기

수수께끼 고양이 2023. 10. 30. 14:19
728x90
반응형

 

딥러닝 목표값 형식을 2진수에서 10진수로 변경

 

_7seg_data.py

import numpy as np

np.set_printoptions(precision=4, suppress=True)

X=np.array([
    [ 1, 1, 1, 1, 1, 1, 0 ], # 0
    [ 0, 1, 1, 0, 0, 0, 0 ], # 1
    [ 1, 1, 0, 1, 1, 0, 0 ], # 2
    [ 1, 1, 1, 1, 0, 0, 1 ], # 3
    [ 0, 1, 1, 0, 0, 1, 1 ], # 4
    [ 1, 0, 1, 1, 0, 1, 1 ], # 5
    [ 0, 0, 1, 1, 1, 1, 1 ], # 6
    [ 1, 1, 1, 0, 0, 0, 0 ], # 7
    [ 1, 1, 1, 1, 1, 1, 1 ], # 8
    [ 1, 1, 1, 0, 0, 1, 1 ] # 9
])
YT=np.array([
    [ 0, 0, 0, 0 ],
    [ 0, 0, 0, 1 ],
    [ 0, 0, 1, 0 ],
    [ 0, 0, 1, 1 ],
    [ 0, 1, 0, 0 ],
    [ 0, 1, 0, 1 ],
    [ 0, 1, 1, 0 ],
    [ 0, 1, 1, 1 ],
    [ 1, 0, 0, 0 ],
    [ 1, 0, 0, 1 ]
])
YT_1=np.array([
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
])

 

예제를 작성한 후 _7seg_data.py 파일이 있는 디렉터리에 저장해 줍니다.

import tensorflow as tf
from _7seg_data import X, YT_1

YT=YT_1

model=tf.keras.Sequential([
    tf.keras.Input(shape=(7,)),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(1, activation='linear')
])

model.compile(optimizer='adam',loss='mse')

model.fit(X,YT,epochs=10000)

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

 

 

 


입력층과 목표층 바꿔보기

import tensorflow as tf
from _7seg_data import X, YT

X, YT=YT, X

model=tf.keras.Sequential([
    tf.keras.Input(shape=(4,)),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(7, activation='linear')
])

model.compile(optimizer='adam',loss='mse')

model.fit(X,YT,epochs=10000)

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

 

 

 


은닉층 늘려보기

import tensorflow as tf
from _7seg_data import X, YT

model=tf.keras.Sequential([
    tf.keras.Input(shape=(7,)),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(4, activation='sigmoid')
])

model.compile(optimizer='adam',loss='mse')

model.fit(X,YT,epochs=10000)

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

 

 


학습시키고 모델 내보내기

import tensorflow as tf
from _7seg_data import X, YT

model=tf.keras.Sequential([
    tf.keras.Input(shape=(7,)),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(4, activation='sigmoid')
])

model.compile(optimizer='adam',loss='mse')

model.fit(X,YT,epochs=10000)

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

 

 

 


모델 불러와 예측하기

1. 

import tensorflow as tf
from _7seg_data import X

model=tf.keras.models.load_model('model7seg.h5')

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

 

 

 

2. 

from tensorflow.keras.models import load_model
from _7seg_data import X

model=load_model('model7seg.h5')

Y=model.predict(X[:1])
print(X[:1].shape)
print(Y)

 

 

 

 

 

 

728x90
반응형