点这里,搜索淘宝优惠券!
点这里,搜索淘宝优惠券!

6 一个工程理解Keras函数式模型-简化版手写字体识别-多层感知器

【理解层对象】

  • 层对象接受张量为参数,返回一个张量。

  • 输入是张量,输出也是张量的一个框架就是一个模型,通过Model定义。

  • 这样的模型可以被像Keras的Sequential一样被训练

【例子】

 1 from keras.layers import Input, Dense
 2 from keras.models import Model
 3 
 4 # This returns a tensor
 5 inputs = Input(shape=(784,))
 6 
 7 # a layer instance is callable on a tensor, and returns a tensor
 8 x = Dense(64, activation='relu')(inputs)
 9 y = Dense(64, activation='relu')(x)
10 z= Dense(10, activation='softmax')(y)
11 
12 # This creates a model that includes
13 # the Input layer and three Dense layers
14 model = Model(inputs=inputs, outputs=z)
15 model.compile(optimizer='rmsprop',
16               loss='categorical_crossentropy',
17               metrics=['accuracy'])

  至此,模型定义完毕。就像层一样,所有的模型都是可调用的。这里像上文中调用Dense一样调用了新定义的model,像上文中一样将张量x作为参数,返回一个张量

1 x = Input(shape=(784,))
2 # This works, and returns the 10-way softmax we defined above.
3 y = model(x)

【利用这两节所学构建一个多输入和多输出模型】

 ?此种情况下损失函数如何计算

【共享层】:当对两个对象做相同的处理,只初始化一个模型,然后像复用函数一样复用它。

   要对不同的输入共享同一层,就初始化该层一次,然后多次调用它.

 1 import keras
 2 from keras.layers import Input, LSTM, Dense #LSTM 长短期记忆网络
 3 from keras.models import Model
 4 
 5 tweet_a = Input(shape=(140, 256))
 6 tweet_b = Input(shape=(140, 256))
 7 # This layer can take as input a matrix
 8 # and will return a vector of size 64
 9 shared_lstm = LSTM(64)
10 
11 # When we reuse the same layer instance
12 # multiple times, the weights of the layer
13 # are also being reused
14 # (it is effectively *the same* layer)
15 encoded_a = shared_lstm(tweet_a)  #复用代码段16 encoded_b = shared_lstm(tweet_b)
17 
18 # We can then concatenate the two vectors: 
19 merged_vector = keras.layers.concatenate([encoded_a, encoded_b], axis=-1)  #连接两个向量
20 
21 # And add a logistic regression on top
22 predictions = Dense(1, activation='sigmoid')(merged_vector)
23 
24 # We define a trainable model linking the
25 # tweet inputs to the predictions
26 model = Model(inputs=[tweet_a, tweet_b], outputs=predictions)
27 
28 model.compile(optimizer='rmsprop',
29               loss='binary_crossentropy',
30               metrics=['accuracy'])
31 model.fit([data_a, data_b], labels, epochs=10)

【层节点的概念】

  无论何时,当你在某个输入上调用层时,你就创建了一个新的张量(即该层的输出),同时你也在为这个层增加一个“(计算)节点”。这个节点将输入张量映射为输出张量。当你多次调用该层时,这个层就有了多个节点

  【例子】

1 a = Input(shape=(140, 256))
2 b = Input(shape=(140, 256))
3 
4 lstm = LSTM(32)
5 encoded_a = lstm(a)
6 encoded_b = lstm(b)
7 
8 lstm.output

  这段代码会报错:AssertionError: Layer lstm has multiple inbound nodes——顾名思义,lstm层有多个节点,访问时须指定下标,使用 get_output_at(node_index)方法。

posted @ 2018-09-05 16:31  chd_ailex  阅读(583)  评论(0编辑  收藏  举报