- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 Keras 中实现 Residual Network 时出现错误。下面是给我错误的代码(错误来自函数定义最后一步的第一行):
加载包:
import numpy as np
from keras import layers
from keras.layers import Input, Add, Concatenate, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D
from keras.models import Model, load_model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
import pydot
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from resnets_utils import *
from keras.initializers import glorot_uniform
import scipy.misc
from matplotlib.pyplot import imshow
%matplotlib inline
import keras.backend as K
K.set_image_data_format('channels_last')
K.set_learning_phase(1)
def identity_block(X, f, filters, stage, block):
"""
Implementation of the identity block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
filters -- python list of integers, defining the number of filters in the CONV layers of the main path
stage -- integer, used to name the layers, depending on their position in the network
block -- string/character, used to name the layers, depending on their position in the network
Returns:
X -- output of the identity block, tensor of shape (n_H, n_W, n_C)
"""
# defining name basis
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
# Save the input value. You'll need this later to add back to the main path.
X_shortcut = X
# First component of main path
X = Conv2D(filters = F1, kernel_size = (1, 1), strides = (1,1), padding = 'valid', name = conv_name_base + '2a', kernel_initializer = glorot_uniform(seed=0))(X)
X = BatchNormalization(axis = 3, name = bn_name_base + '2a')(X)
X = Activation('relu')(X)
# Second component of main path
X = Conv2D(filters=F2, kernel_size=(f,f),strides=(1,1),padding='same',name=conv_name_base+'2b',kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization(axis=3,name=bn_name_base+'2b')(X)
X = Activation('relu')(X)
# Third component of main path
X = Conv2D(filters=F3,kernel_size=(1,1),strides=(1,1),padding='valid',name=conv_name_base+'2c',kernel_initializer=glorot_uniform(seed=0))(X)
print(f'before BatchNormalization: X={X}');X = BatchNormalization(axis=3,name=bn_name_base+'2c');print(f'after BatchNormalization: X={X}');
# Final step: Add shortcut value to main path, and pass it through a RELU activation
X = Add()([X_shortcut,X])
X = Activation('relu')(X)
### END CODE HERE ###
return X
tf.reset_default_graph()
with tf.Session() as test:
np.random.seed(1)
A_prev = tf.placeholder("float", [3, 4, 4, 6])
X = np.random.randn(3, 4, 4, 6)
A = identity_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
test.run(tf.global_variables_initializer())
out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
print("out = " + str(out[0][1][1][0]))
<keras.layers.normalization.BatchNormalization object at 0x7f169c6d9668>
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.normalization.BatchNormalization'>`. Expected a symbolic tensor instance.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/keras/engine/topology.py in assert_input_compatibility(self, inputs)
424 try:
--> 425 K.is_keras_tensor(x)
426 except ValueError:
/opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in is_keras_tensor(x)
399 tf.SparseTensor)):
--> 400 raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) + '`. '
401 'Expected a symbolic tensor instance.')
ValueError: Unexpectedly found an instance of type `<class 'keras.layers.normalization.BatchNormalization'>`. Expected a symbolic tensor instance.
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-6-b3d1050f50dc> in <module>()
5 A_prev = tf.placeholder("float", [3, 4, 4, 6])
6 X = np.random.randn(3, 4, 4, 6)
----> 7 A = identity_block(A_prev, f = 2, filters = [2, 4, 6], stage = 1, block = 'a')
8 test.run(tf.global_variables_initializer())
9 out = test.run([A], feed_dict={A_prev: X, K.learning_phase(): 0})
<ipython-input-5-013941ce79d6> in identity_block(X, f, filters, stage, block)
43
44 # Final step: Add shortcut value to main path, and pass it through a RELU activation (≈2 lines)
---> 45 X = Add()([X_shortcut,X])
46 X = Activation('relu')(X)
47
/opt/conda/lib/python3.6/site-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs)
556 # Raise exceptions in case the input is not compatible
557 # with the input_spec specified in the layer constructor.
--> 558 self.assert_input_compatibility(inputs)
559
560 # Collect input shapes to build layer.
/opt/conda/lib/python3.6/site-packages/keras/engine/topology.py in assert_input_compatibility(self, inputs)
429 'Received type: ' +
430 str(type(x)) + '. Full input: ' +
--> 431 str(inputs) + '. All inputs to the layer '
432 'should be tensors.')
433
ValueError: Layer add_1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.layers.normalization.BatchNormalization'>. Full input: [<tf.Tensor 'Placeholder:0' shape=(3, 4, 4, 6) dtype=float32>, <keras.layers.normalization.BatchNormalization object at 0x7f169c6d9668>]. All inputs to the layer should be tensors.
最佳答案
永远记住将张量传递到层中:
print(f'before BatchNormalization: X={X}');
#X = BatchNormalization(axis=3,name=bn_name_base+'2c') # <--- INCORRECT
X = BatchNormalization(axis=3,name=bn_name_base+'2c')(X) # <--- CORRECT
print(f'after BatchNormalization: X={X}');
X
时将该层评估为张量.
identity_block()
缺少返回,这将引发另一个错误;添加:
return X
.最后,
F1, F2, F3
既未在函数内定义,也未作为参数传递 - 您可能不会将其视为错误,因为它们是在函数外部定义的 - 例如在您的本地命名空间中。
关于keras - 意外地发现了一个 BatchNormalization 类型的实例。期望符号张量实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57931067/
BatchNormalization 和 TimeDistributed(BatchNormalization) 是否对顺序数据(例如视频)有相同的影响?如果不是有什么区别? 最佳答案 在 tf.ke
我正在尝试将预训练的 BN 权重从 pytorch 模型复制到其等效的 Keras 模型,但我不断得到不同的输出。 我阅读了 Keras 和 Pytorch BN 文档,我认为区别在于它们计算“均值”
我有两种类型的灰度图像,比如汽车和飞机。在我的训练集中,我有 1000 张图像(大约 50/50 分割)。在这个训练集中,我所有的飞机示例都在白色背景上,而所有汽车示例都在黑色背景上(这是故意的,模型
我正在训练一个 CNN,为了调试我的问题,我正在研究实际训练数据的一小部分。 在训练期间,损失和准确性似乎非常合理且相当不错。 (在示例中我使用了相同的小子集进行验证,问题已经在这里显示了) 适合 x
我有这些 Backprop 更新,请让我知道 dx 部分哪里出了问题。在计算图中,我使用X、sample_mean 和sample_var。感谢您的帮助 (x, norm, sample_mean,
我对如何使用/插入"BatchNorm"有点困惑我的模型中的图层。 我看到了几种不同的方法,例如: ResNets : "BatchNorm"+"Scale" (无参数共享) “BatchNorm”
我想弄清楚 Keras 中的批量归一化究竟做了什么。现在我有以下代码。 for i in range(8): c = Convolution2D(128, 3, 3, border_mode
我正在尝试将批量规范添加到 Keras 中的 vgg 样式模型。当我添加 batch norm 层时,出现错误: FailedPreconditionError: Attempting to use
keras BatchNormalization layer使用 axis=-1 作为默认值,并说明特征轴通常是归一化的。为什么会这样? 我想这很令人惊讶,因为我更熟悉使用类似 StandardSca
是 batchnorm momentum convention (默认值=0.1)与其他库一样正确,例如Tensorflow 好像一般默认是 0.9 或者 0.99?或者也许我们只是使用了不同的约定?
在 Keras 中实现 Residual Network 时出现错误。下面是给我错误的代码(错误来自函数定义最后一步的第一行): 加载包: import numpy as np from keras
我正在尝试保存模型,然后稍后加载它以进行一些预测;发生的事情是训练后模型的准确率是95%+ ,但是当我保存它然后加载它时,准确度下降到接近 10%在 同 数据集。 要重现此错误结果,您可以运行 thi
我有以下代码。 x = keras.layers.Input(batch_shape = (None, 4096)) hidden = keras.layers.Dense(512, activati
我正在通过时间序列数据训练 LSTM 网络,并希望对数据进行标准化,因为我的特征具有不同的规模。 我的数据形状是 (n_samples x n_timestamps x n_features) 我想使
我目前正在学习在我的项目中使用 Tensorflow-2.0。我想使用卷积神经网络(CNN)完成一个语义分割任务,在编码时发现一个奇怪的错误。 首先,构建了一个简单的模型并且运行良好。 X_train
我的问题是 BatchNormalization (BN) 正在标准化什么。 我问,BN 是单独对每个像素的 channel 进行归一化,还是对所有像素一起归一化。它是在每个图像的基础上还是在整个批处
我的 LSTM 网络有 5 个输入。第一个输入的典型值为 1000 到 3000。其余输入的值为 -1 到 1。 我想插入 BatchNormalization 作为第一层。但输入 2-5 已经在 -
inputs = Input((img_height, img_width, img_ch)) conv1 = Conv2D(n_filters, (k, k), padding=padding)(i
我正在尝试使用 Tensorflow 从 GAN 保存生成器模型。我正在使用的模型有几个批量归一化层。当我保存权重时,只有运行全局变量初始值设定项才能成功恢复它们,但我不必这样做,因为所有变量都正在恢
过了一段时间我又回到了tensorflow,看起来情况已经完全改变了。 但是,之前我曾经在训练循环中使用 tf.contrib....batch_normalization 并进行以下操作: upda
我是一名优秀的程序员,十分优秀!