{ "cells": [ { "cell_type": "markdown", "id": "df1f5eb3", "metadata": {}, "source": [ "# demonstration of broadcasting in tensorflow" ] }, { "cell_type": "code", "execution_count": null, "id": "1d61c70a", "metadata": {}, "outputs": [], "source": [ "import tensorflow as tf" ] }, { "cell_type": "code", "execution_count": null, "id": "38bca1cf", "metadata": {}, "outputs": [], "source": [ "# Define two tensors with different shapes\n", "a = tf.constant([[1, 2, 3], [4, 5, 6]])\n", "b = tf.constant([10, 20, 30])" ] }, { "cell_type": "code", "execution_count": null, "id": "c3f382e3", "metadata": {}, "outputs": [], "source": [ "# Perform element-wise multiplication using broadcasting\n", "c = a * b\n", "# Print the result\n", "print(c)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "95683fe5", "metadata": {}, "outputs": [], "source": [ "# Broadcasting scalar to tensor\n", "x = tf.constant([1, 2, 3])\n", "y = 2\n", "z = x + y # equivalent to tf.add(x, y)\n", "print(z.numpy()) # [3 4 5]" ] }, { "cell_type": "code", "execution_count": null, "id": "8ed98565", "metadata": {}, "outputs": [], "source": [ "# Broadcasting vector to matrix\n", "x = tf.constant([[1, 2], [3, 4]])\n", "y = tf.constant([1, 2])\n", "z = x + y # equivalent to tf.add(x, y)\n", "print(z.numpy()) # [[2 4], [4 6]]" ] }, { "cell_type": "code", "execution_count": null, "id": "41f4196f", "metadata": {}, "outputs": [], "source": [ "# Broadcasting matrix to tensor\n", "x = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])\n", "y = tf.constant([[1], [2]])\n", "z = x + y # equivalent to tf.add(x, y)\n", "print(z.numpy()) # [[[2 3], [4 5]], [[7 8], [9 10]]]" ] }, { "cell_type": "code", "execution_count": null, "id": "76a5108d", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "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.8.16" } }, "nbformat": 4, "nbformat_minor": 5 }