Machine Learning Kurs im Rahmen der Studierendentage im SS 2023
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
1.9 KiB

2 years ago
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "code",
  5. "execution_count": null,
  6. "id": "eefe7571",
  7. "metadata": {},
  8. "outputs": [],
  9. "source": [
  10. "# show differentiation in Tensorflow"
  11. ]
  12. },
  13. {
  14. "cell_type": "code",
  15. "execution_count": null,
  16. "id": "a9d7c185",
  17. "metadata": {},
  18. "outputs": [],
  19. "source": [
  20. "import tensorflow as tf"
  21. ]
  22. },
  23. {
  24. "cell_type": "code",
  25. "execution_count": null,
  26. "id": "584384f1",
  27. "metadata": {},
  28. "outputs": [],
  29. "source": [
  30. "# Define a function to differentiate\n",
  31. "def f(x):\n",
  32. " return x ** 2 + 2 * x + 1"
  33. ]
  34. },
  35. {
  36. "cell_type": "code",
  37. "execution_count": null,
  38. "id": "70430402",
  39. "metadata": {},
  40. "outputs": [],
  41. "source": [
  42. "# Create a TensorFlow variable\n",
  43. "x = tf.Variable(2.0)"
  44. ]
  45. },
  46. {
  47. "cell_type": "code",
  48. "execution_count": null,
  49. "id": "45ea0a33",
  50. "metadata": {},
  51. "outputs": [],
  52. "source": [
  53. "# Use tf.GradientTape to record the gradients\n",
  54. "with tf.GradientTape() as tape:\n",
  55. " y = f(x)"
  56. ]
  57. },
  58. {
  59. "cell_type": "code",
  60. "execution_count": null,
  61. "id": "f6b1ff27",
  62. "metadata": {},
  63. "outputs": [],
  64. "source": [
  65. "# Calculate the gradient of y with respect to x\n",
  66. "dy_dx = tape.gradient(y, x)"
  67. ]
  68. },
  69. {
  70. "cell_type": "code",
  71. "execution_count": null,
  72. "id": "4f581817",
  73. "metadata": {},
  74. "outputs": [],
  75. "source": [
  76. "# Print the result\n",
  77. "print(dy_dx)"
  78. ]
  79. }
  80. ],
  81. "metadata": {
  82. "kernelspec": {
  83. "display_name": "Python 3 (ipykernel)",
  84. "language": "python",
  85. "name": "python3"
  86. },
  87. "language_info": {
  88. "codemirror_mode": {
  89. "name": "ipython",
  90. "version": 3
  91. },
  92. "file_extension": ".py",
  93. "mimetype": "text/x-python",
  94. "name": "python",
  95. "nbconvert_exporter": "python",
  96. "pygments_lexer": "ipython3",
  97. "version": "3.8.16"
  98. }
  99. },
  100. "nbformat": 4,
  101. "nbformat_minor": 5
  102. }