teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

d

2019/03/27 14:03

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -34,4 +34,46 @@
34
34
  #plot_model(model, to_file='model.png', show_shapes=True)
35
35
  ```
36
36
 
37
- ![イメージ説明](2410621e429d64df1f7837b611a405f5.png)
37
+ ![イメージ説明](2410621e429d64df1f7837b611a405f5.png)
38
+
39
+ ## 追記
40
+
41
+ 2つの出力を持つモデルでそれぞれ異なる損失関数を使用する方法
42
+
43
+ ```python
44
+ from keras.layers import Input, Dense
45
+ from keras.models import Model
46
+ from keras import backend as K
47
+
48
+ def encoder(input_):
49
+ d1 = Dense(10, activation="relu")(input_)
50
+ d2 = Dense(10, activation="relu")(d1)
51
+ d3 = Dense(10)(d2)
52
+ return d3
53
+
54
+
55
+ def decoder(input_):
56
+ d1 = Dense(10, activation="relu")(input_)
57
+ d2 = Dense(10, activation="relu")(d1)
58
+ d3 = Dense(10)(d2)
59
+ return d3
60
+
61
+
62
+ input1 = Input(shape=(100,))
63
+ input2 = Input(shape=(100,))
64
+
65
+ output1 = encoder(input1)
66
+ output2 = encoder(input2)
67
+
68
+ # モデルは適当なので、適宜変更してください。
69
+ model = Model(inputs=[input1, input2], outputs=[output1, output2])
70
+
71
+ def my_loss_function(y_pred, y_true):
72
+ # (Batchsize,) のテンソルを返す自作の損失関数
73
+ # 以下は適当なので、適宜変更してください。
74
+ return K.mean(K.square(y_pred - y_true), axis=-1)
75
+
76
+ model.compile(loss=['mean_squared_error', my_loss_function], # output1, output2 の出力に対応する損失関数
77
+ loss_weights=[1.0, 1.0], # 損失関数を足し合わせる際の重み
78
+ optimizer='adam')
79
+ ```