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 深度学习入门