{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eefe7571",
   "metadata": {},
   "outputs": [],
   "source": [
    "# show differentiation in Tensorflow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9d7c185",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "584384f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define a function to differentiate\n",
    "def f(x):\n",
    "    return x ** 2 + 2 * x + 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70430402",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a TensorFlow variable\n",
    "x = tf.Variable(2.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45ea0a33",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use tf.GradientTape to record the gradients\n",
    "with tf.GradientTape() as tape:\n",
    "    y = f(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6b1ff27",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Calculate the gradient of y with respect to x\n",
    "dy_dx = tape.gradient(y, x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f581817",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Print the result\n",
    "print(dy_dx)"
   ]
  }
 ],
 "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
}
