我有以下类,该类由网络组成,该网络接受具有给定形状的给定np.array输入,并返回具有相同形状的输出。我想实现一个需要三个参数的自定义损失。为此,我使用Keras方法.add_loss,但似乎引发错误。 我正在使用的类如下(简化):
class Net():
def __init__(self, **kwargs: dict):
self._input_shape = kwargs.get('input_shape', (12, 86, 98,1))
def _build(self):
"""
This method generates the output x.
"""
inputs = Input(shape = self._input_shape)
x = self.f1(inputs)
x = self.f2(x)
self.get_optimiser()
model = self.get_loss(inputs, x)
return model
def f1(self, inputs):
return inputs
def f2(self, inputs):
return inputs
def get_optimiser(self):
self._optimiser = SGD(lr = self._learnrate, momentum = self._momentum, decay = self._decay, nesterov = False)
def get_loss(self, inputs, outputs):
self._model = Model(inputs=[inputs], outputs=[outputs])
y_true = Input(self._input_shape, name = 'y_true')
is_weight = Input(self._input_shape, name = 'is_weight')
self._model = Model(inputs=[inputs, y_true, is_weight], outputs=[outputs])
self._model.add_loss(weighted_dice_loss(y_true, outputs, is_weight))
self._model.compile(optimizer = self._optimiser, loss = None, metrics = [dice_coef])
return self._model
但是,在实例化类并运行_build方法后:
net = Net()
net._build()
我抛出以下错误:
<ipython-input-124-46b9e7f916ce> in _build(self)
50
51 self.get_optimiser()
---> 52 model = self.get_loss(inputs, x)
53
54 return model
<ipython-input-124-46b9e7f916ce> in get_loss(self, inputs, outputs)
151 model = Model(inputs=[inputs, y_true, is_weight], outputs=[outputs])
152
--> 153 model.add_loss(weighted_dice_loss(y_true, outputs, is_weight))
154 self._model.compile(optimizer = self._optimiser, loss = None, metrics = [dice_coef])
155
~/miniconda3/envs/segment/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in add_loss(self, losses, inputs)
899 eager_losses.append(_tag_unconditional(loss))
900
--> 901 self._callable_losses += callable_losses
902
903 call_context = base_layer_utils.is_in_call_context()
AttributeError: 'Model' object has no attribute '_callable_losses'
编辑 我已经将tensorflow更新到v 2.2.0,并且正在导入以下模块:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Input, optimizers
from tensorflow.keras.models import Sequential, load_model
from keras.layers.convolutional import Conv3D, Conv3DTranspose
from keras.layers.normalization import BatchNormalization
from keras.layers import Cropping3D, UpSampling3D, AveragePooling3D
现在抛出的错误已更改为:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-c4c292a59224> in <module>
11
12
---> 13 unet_model = unet._build()
<ipython-input-2-9245d04f54db> in _build(self)
44 inputs = Input(shape = self._input_shape)
45
---> 46 x = self.first_layers(inputs)
47 x = self.contractive_path(x)
48 x = self.middle_path(x)
<ipython-input-2-9245d04f54db> in first_layers(self, inputs)
57
58 layer = Conv3D(filters = self._n_filters, kernel_size = self._patch, activation = self._activation, kernel_initializer = self._kernel_initializer,
---> 59 padding = self._padding)(inputs)
60
61 return layer
~/miniconda3/envs/segment/lib/python3.7/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
89 warnings.warn('Update your `' + object_name + '` call to the ' +
90 'Keras 2 API: ' + signature, stacklevel=2)
---> 91 return func(*args, **kwargs)
92 wrapper._original_function = func
93 return wrapper
~/miniconda3/envs/segment/lib/python3.7/site-packages/keras/layers/convolutional.py in __init__(self, filters, kernel_size, strides, padding, data_format, dilation_rate, activation, use_bias, kernel_initializer, bias_initializer, kernel_regularizer, bias_regularizer, activity_regularizer, kernel_constraint, bias_constraint, **kwargs)
617 kernel_constraint=kernel_constraint,
618 bias_constraint=bias_constraint,
--> 619 **kwargs)
620
621 def get_config(self):
~/miniconda3/envs/segment/lib/python3.7/site-packages/keras/layers/convolutional.py in __init__(self, rank, filters, kernel_size, strides, padding, data_format, dilation_rate, activation, use_bias, kernel_initializer, bias_initializer, kernel_regularizer, bias_regularizer, activity_regularizer, kernel_constraint, bias_constraint, **kwargs)
103 bias_constraint=None,
104 **kwargs):
--> 105 super(_Conv, self).__init__(**kwargs)
106 self.rank = rank
107 self.filters = filters
~/miniconda3/envs/segment/lib/python3.7/site-packages/keras/engine/base_layer.py in __init__(self, **kwargs)
130 if not name:
131 prefix = self.__class__.__name__
--> 132 name = _to_snake_case(prefix) + '_' + str(K.get_uid(prefix))
133 self.name = name
134
~/miniconda3/envs/segment/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in get_uid(prefix)
72 """
73 global _GRAPH_UID_DICTS
---> 74 graph = tf.get_default_graph()
75 if graph not in _GRAPH_UID_DICTS:
76 _GRAPH_UID_DICTS[graph] = defaultdict(int)
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'