简体   繁体   English

如何在 tensorflow 中实现自定义不可训练的卷积过滤器?

[英]How do you implement a custom non-trainable Convolution filter in tensorflow?

Using the x-direction sobel filter as an example, how do you implement a non-trainable Convolutional Filter with weights: [[-1, 0, +1],[-2, 0, +2],[-1, 0, +1]] in tensorflow?以 x 方向 sobel 滤波器为例,如何实现一个不可训练的卷积滤波器,其权重为:[[-1, 0, +1],[-2, 0, +2],[-1, 0 , +1]] 在 tensorflow 中?

I would recommend using tf.nn.conv2d if you want full flexibility in applying filters:如果你想要完全灵活地应用过滤器,我会推荐使用tf.nn.conv2d

import tensorflow as tf
import matplotlib.pyplot as plt
import pathlib

dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  seed=123,
  image_size=(180, 180),
  shuffle=False,
  batch_size=2)
images, _ = next(iter(ds.take(1)))

sobel_filter = tf.tile(tf.reshape(tf.constant([[-1, 0, +1],[-2, 0, +2],[-1, 0, +1]], dtype=tf.float32), (3, 3, 1, 1)), [1, 1, 3, 3])
y = tf.nn.conv2d(tf.expand_dims(images[0], axis=0), sobel_filter, strides=[1, 1, 1, 1], padding='SAME')

plt.figure()
f, axarr = plt.subplots(1,2) 
axarr[0].imshow(images[0]/ 255)
axarr[1].imshow(y[0] / 255)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 梯度会流过张量流中不可训练的变量吗? - Do gradients flow through non-trainable variables in tensorflow? PyTorch 中的卷积与不可训练的预定义 kernel - Convolution in PyTorch with non-trainable pre-defined kernel 如何将 keras 中的参数设置为不可训练? - How to set parameters in keras to be non-trainable? Tensorflow:更新不可训练模型层的权重 - Tensorflow: Weights of non-trainable model layers are updated 无法在 Tensorflow v2 中创建不可训练的变量 - Can't Create Non-Trainable Variables in Tensorflow v2 在 TensorFlow Keras 中仅将偏差设置为不可训练 - Set only the bias to be non-trainable in TensorFlow Keras Keras 自定义层参数是否默认不可训练? - Are Keras custom layer parameters non-trainable by default? 如何将特定的 keras 层权重定义为不可训练? - How to define a specific keras layer weight as non-trainable? 如何在 tf.Estimator 检查点中保留不可训练的变量? - How to persist non-trainable variables in tf.Estimator checkpoint? 来自 tensorflow.keras.layers.experimental 中的 preprocessing.Normalization 的摘要中的不可训练参数是如何计算的? - How are the non-trainable parameters in the summary coming from preprocessing.Normalization in tensorflow.keras.layers.experimental calculated?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM