Я извлекаю код из проекта https://github.com/vanvalenlab/deepcell-tf/tree/master/deepcell, чтобы попробовать свои силы в применении CNN для маркировки 2D-изображений по пикселям. Я взял соответствующий код и организовал его в блокнот Google Colab;все работает, пока я не столкнусь с ошибкой FailedPreconditionError:
FailedPreconditionError: 2 root error(s) found.
(0) Failed precondition: Attempting to use uninitialized value image_normalization2d_15/Variable
[[{{node image_normalization2d_15/Variable/read}}]]
[[metrics/model_12_acc/Identity/_1817]]
(1) Failed precondition: Attempting to use uninitialized value image_normalization2d_15/Variable
[[{{node image_normalization2d_15/Variable/read}}]]
0 successful operations.
0 derived errors ignored.
"image_normalization2d" - это класс фильтров, которые я буду применять к своим изображениям:
class ImageNormalization2D(Layer):
def __init__(self, norm_method='std', filter_size=61, data_format=None, **kwargs):
super(ImageNormalization2D, self).__init__(**kwargs)
self.filter_size = filter_size
self.norm_method = norm_method
self.data_format = conv_utils.normalize_data_format(data_format)
if self.data_format == 'channels_first':
self.channel_axis = 1
else:
self.channel_axis = 3 # hardcoded for 2D data
if isinstance(self.norm_method, str):
self.norm_method = self.norm_method.lower()
def compute_output_shape(self, input_shape):
input_shape = tensor_shape.TensorShape(input_shape).as_list()
return tensor_shape.TensorShape(input_shape)
def _average_filter(self, inputs):
in_channels = inputs.shape[self.channel_axis]
W = np.ones((self.filter_size, self.filter_size, in_channels, 1))
W /= W.size
kernel = tf.Variable(W.astype(K.floatx()))
if self.data_format == 'channels_first':
inputs = tf.transpose(inputs, perm=[0, 2, 3, 1])
outputs = tf.nn.depthwise_conv2d(inputs, kernel, [1, 1, 1, 1],
padding='SAME', data_format='NHWC')
if self.data_format == 'channels_first':
outputs = tf.transpose(outputs, perm=[0, 3, 1, 2])
return outputs
def call(self, inputs):
if not self.norm_method:
outputs = inputs
elif self.norm_method == 'std':
outputs = inputs - self._average_filter(inputs)
outputs /= self._window_std_filter(outputs)
elif self.norm_method == 'max':
outputs = inputs / tf.reduce_max(inputs)
outputs -= self._average_filter(outputs)
elif self.norm_method == 'median':
reduce_axes = list(range(len(inputs.shape)))[1:]
reduce_axes.remove(self.channel_axis)
# mean = self._reduce_median(inputs, axes=reduce_axes)
mean = tf.contrib.distributions.percentile(inputs, 50.)
outputs = inputs / mean
outputs -= self._average_filter(outputs)
else:
raise NotImplementedError('"{}" is not a valid norm_method'.format(self.norm_method))
return outputs
def get_config(self):
config = {
'norm_method': self.norm_method,
'filter_size': self.filter_size,
'data_format': self.data_format
}
base_config = super(ImageNormalization2D, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
И я использую этокласс при построении сети объектов:
def bn_feature_net_skip_2D(receptive_field=61,
input_shape=(256, 256, 1),
fgbg_model=None,
n_skips=2,
last_only=True,
norm_method='std',
padding_mode='reflect',
**kwargs):
if K.image_data_format() == 'channels_first':
channel_axis = 1
else:
channel_axis = -1
inputs = Input(shape=input_shape)
img = ImageNormalization2D(norm_method=norm_method, filter_size=receptive_field)(inputs)
models = []
model_outputs = []
if fgbg_model is not None:
for layer in fgbg_model.layers:
layer.trainable = False
models.append(fgbg_model)
fgbg_output = fgbg_model(inputs)
if isinstance(fgbg_output, list):
fgbg_output = fgbg_output[-1]
model_outputs.append(fgbg_output)
for _ in range(n_skips + 1):
if model_outputs:
model_input = Concatenate(axis=channel_axis)([img, model_outputs[-1]])
else:
model_input = img
new_input_shape = model_input.get_shape().as_list()[1:]
models.append(bn_feature_net_2D(receptive_field=receptive_field, input_shape=new_input_shape, norm_method=None, dilated=True, padding=True, padding_mode=padding_mode, **kwargs))
model_outputs.append(models[-1](model_input))
if last_only:
model = Model(inputs=inputs, outputs=model_outputs[-1])
else:
if fgbg_model is None:
model = Model(inputs=inputs, outputs=model_outputs)
else:
model = Model(inputs=inputs, outputs=model_outputs[1:])
return model
Когда я на самом деле пытаюсь обучить алгоритм и сеть объектов, я получаю сообщение об ошибке.
Я пытался привести переменную "img", которая содержит класс фильтра ImageNormalization2D, как объект tenorflow.Variable, но, похоже, это не решает проблему. Я также попытался вставить `
init_op = tf.globalize_all_variables()
sess = tf.Session()
sess.run(init_op)
` и подобный код в разных местах без какого-либо успеха. Буду признателен за любые предложения!