Keras로 시작하는 딥 러닝
Miguel Esteban
Data Scientist & Founder
# Keras 모델의 첫 레이어 접근 first_layer = model.layers[0]# 레이어 및 입력, 출력, 가중치 출력 print(first_layer.input) print(first_layer.output) print(first_layer.weights)
<tf.Tensor 'dense_1_input:0' shape=(?, 3) dtype=float32>
<tf.Tensor 'dense_1/Relu:0' shape=(?, 2) dtype=float32>
[<tf.Variable 'dense_1/kernel:0' shape=(3, 2) dtype=float32_ref>,
<tf.Variable 'dense_1/bias:0' shape=(2,) dtype=float32_ref>]
# 랭크 2 텐서(2차원) 정의 T2 = [[1,2,3], [4,5,6], [7,8,9]]# 랭크 3 텐서(3차원) 정의 T3 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15], [16,17,18], [19,20,21], [22,23,24], [25,26,27]]
# Keras 백엔드 임포트 import tensorflow.keras.backend as K# 모델 레이어의 입력/출력 텐서 가져오기 inp = model.layers[0].input out = model.layers[0].output# 레이어 입력을 출력으로 매핑하는 함수 inp_to_out = K.function([inp], [out])# 입력을 주면 첫 레이어의 출력을 반환 print(inp_to_out([X_train])
# X_train 각 샘플의 첫 레이어 출력
[array([[0.7, 0],...,[0.1, 0.3]])]




# 순차 모델 생성 autoencoder = Sequential()# 은닉층 4개 뉴런, 입력층 100 추가 autoencoder.add(Dense(4, input_shape=(100,), activation='relu'))# 출력층 100개 뉴런 추가 autoencoder.add(Dense(100, activation='sigmoid'))# 적절한 손실로 컴파일 autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
# 입력을 인코딩하는 별도 모델 구성 encoder = Sequential() encoder.add(autoencoder.layers[0])# 예측은 은닉층 4개 뉴런의 출력을 반환 encoder.predict(X_test)
# X_test 각 샘플에 대한 숫자 4개
array([10.0234375, 5.833543, 18.90444, 9.20348],...)
Keras로 시작하는 딥 러닝