回答編集履歴
1
回答になっていませんでした。
test
CHANGED
@@ -1,15 +1,61 @@
|
|
1
1
|
```Python
|
2
2
|
|
3
|
+
class CategoricalCrossentropy1(keras.losses.Loss):
|
4
|
+
|
5
|
+
def __init__(self, steps_per_epoch=None, end_epoch=None, name="example"):
|
6
|
+
|
7
|
+
super().__init__(name=name)
|
8
|
+
|
9
|
+
self.steps_per_epoch, self.end_epoch = steps_per_epoch, end_epoch
|
10
|
+
|
11
|
+
|
12
|
+
|
13
|
+
self.step = tf.Variable(0.)
|
14
|
+
|
15
|
+
def call(self, y_true, y_pred):
|
16
|
+
|
17
|
+
epoch = self.step/self.steps_per_epoch
|
18
|
+
|
19
|
+
|
20
|
+
|
21
|
+
if epoch < self.end_epoch:
|
22
|
+
|
23
|
+
weight=1.0
|
24
|
+
|
25
|
+
else:
|
26
|
+
|
27
|
+
weight=-1.0 #Note that extreme number was put here to check how this code work
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
loss = -tf.reduce_sum(weight*y_true*tf.math.log(y_pred)) #impose weight on CategoricalCrossentropy
|
32
|
+
|
33
|
+
|
34
|
+
|
35
|
+
self.step.assign(self.step + 1) # add to step
|
36
|
+
|
37
|
+
|
38
|
+
|
39
|
+
return loss
|
40
|
+
|
41
|
+
```
|
42
|
+
|
43
|
+
どうでしょうか
|
44
|
+
|
45
|
+
|
46
|
+
|
47
|
+
```Python
|
48
|
+
|
3
|
-
loss_weight =
|
49
|
+
loss_weight = tf.Variable(1.0)
|
4
50
|
|
5
51
|
model.compile(loss=CategoricalCrossentropy1(steps_per_epoch, end_epoch),optimizer=keras.optimizers.SGD(),loss_weights=(loss_weight,))
|
6
52
|
|
7
53
|
|
8
54
|
|
9
|
-
|
55
|
+
loss_weight.assign(1.5)#値の更新方法
|
10
56
|
|
11
57
|
```
|
12
58
|
|
13
|
-
|
59
|
+
loss_weightsにテンソルを渡して、それを更新するという方法もあるかと思います。
|
14
60
|
|
15
61
|
値の更新はkeras.callbacks.Callbackを継承したクラスに更新処理を書いてmodel.fit時に渡す。または、model.train_on_batchで書き換えて、iter処理中に書くかという方法があるかと思います。
|