python - 为什么会出现这个错误:"Sliced assignment is only supported for variables"

标签 python tensorflow keras tensor

我有一个使用 Keras 的深层网络,我需要对一层的输出进行裁剪,然后发送到下一层。为此,我将以下代码编写为 lambda 层:

def cropping_fillzero(img, rate=0.6): # Q = percentage
    residual_shape = img.get_shape().as_list()
    h, w = residual_shape[1:3]
    blacked_pixels = int((rate) * (h*w))
    ratio = int(np.floor(np.sqrt(blacked_pixels)))
#    width = int(np.ceil(np.sqrt(blacked_pixels)))

    x = np.random.randint(0, w - ratio)
    y = np.random.randint(0, h - ratio)
    cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))

    return cropingImg

decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate}, name='residual_cropout_attack')(bncv11)

但它产生以下错误,我不知道为什么?!

Traceback (most recent call last):

File "", line 1, in runfile('E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py', wdir='E:/code_v28-7-19')

File "D:\software\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile execfile(filename, namespace)

File "D:\software\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py", line 143, in decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate}, name='residual_cropout_attack')(bncv11)

File "D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\base_layer.py", line 457, in call output = self.call(inputs, **kwargs)

File "D:\software\Anaconda3\envs\py36\lib\site-packages\keras\layers\core.py", line 687, in call return self.function(inputs, **arguments)

File "E:/code_v28-7-19/CIFAR_los4x4convolvedw_5_cropAttack_RandomSize_Pad.py", line 48, in cropping_fillzero cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio]))

File "D:\software\Anaconda3\envs\py36\lib\site-packages\tensorflow\python\ops\array_ops.py", line 700, in assign raise ValueError("Sliced assignment is only supported for variables")

ValueError: Sliced assignment is only supported for variables

您能告诉我如何解决这个错误吗? 谢谢

最佳答案

h, w =残差形状[1:3]

我不完全确定你想在这里做什么,但Python将其解释为“第二个元素和第四个元素之间的返回”。也许您的意思是residual_shape[1]、residual_shape[3]

关于python - 为什么会出现这个错误:"Sliced assignment is only supported for variables",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57377905/

相关文章:

python - 在 Windows 上用 Python 打开设备句柄

python - Tkinter 按键触发事件

python - 二维数据的 Keras 内置 MSE 损失返回二维矩阵,而不是标量损失

python - 创建输出两个 Y 变量的 LSTM 神经网络

python - 带有 tf 数据集输入的 Tensorflow keras

python - 为什么当我 np.array (图像)时出现 reshape 错误

python - 计算机因大量 Python 异步 aiohttp 请求而挂起

python - GradienTape 收敛速度比 Keras.model.fit 慢得多

python - Tensorflow:没有为标准操作注册形状函数:ExtractGlimpse。在哪里添加形状函数的代码?

python - 在 Tensorflow 中为自定义静态张量保留未知的批处理维度