Skip to content

Instantly share code, notes, and snippets.

@3zhang
Created September 27, 2022 13:40
Show Gist options
  • Save 3zhang/1b3e80a3673e0a5bbb63252150bc6ece to your computer and use it in GitHub Desktop.
Save 3zhang/1b3e80a3673e0a5bbb63252150bc6ece to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "46a75b69",
"metadata": {},
"source": [
"Convolution in tensorflow is actually cross-correlation. \n",
"First execute 2D convolution in tensorflow:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "b93b7ad9",
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"import numpy as np\n",
"from scipy.signal import convolve\n",
"\n",
"X = np.random.randint(0,10, (7,6,5))\n",
"F = np.random.randint(0,10, (4,3,2))\n",
"\n",
"Xt = tf.constant(X, dtype=tf.float32)\n",
"Xt = tf.reshape(Xt, [1]+Xt.shape+[1])\n",
"Ft = tf.constant(F, dtype=tf.float32)\n",
"Ft = tf.reshape(Ft, Ft.shape+[1,1])\n",
"\n",
"Zt = tf.nn.convolution(Xt, Ft, padding='VALID')\n",
"Zt = tf.squeeze(Zt)"
]
},
{
"cell_type": "markdown",
"id": "42922357",
"metadata": {},
"source": [
"Then flip the filter and do convolution in Scipy."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "efe274c0",
"metadata": {},
"outputs": [],
"source": [
"Z = convolve(X, np.flip(F), 'valid')"
]
},
{
"cell_type": "markdown",
"id": "a7a3ed3f",
"metadata": {},
"source": [
"They give the same result:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "4f4d00b3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.0\n"
]
}
],
"source": [
"print(np.linalg.norm(Z - Zt.numpy()))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (Spyder)",
"language": "python3",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment