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.

247 lines
7.3 KiB

2 years ago
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "code",
  5. "execution_count": null,
  6. "id": "344b183c",
  7. "metadata": {},
  8. "outputs": [],
  9. "source": [
  10. "#\n",
  11. "# train a simple TensorFlow model to perform binary classification on a generated\n",
  12. "# 2-dimensional dataset \n",
  13. "# 02/2023\n",
  14. "# "
  15. ]
  16. },
  17. {
  18. "cell_type": "code",
  19. "execution_count": null,
  20. "id": "92c9d0a1",
  21. "metadata": {},
  22. "outputs": [],
  23. "source": [
  24. "import numpy as np\n",
  25. "import matplotlib.pyplot as plt\n",
  26. "import tensorflow as tf"
  27. ]
  28. },
  29. {
  30. "cell_type": "code",
  31. "execution_count": null,
  32. "id": "3814ea1d",
  33. "metadata": {},
  34. "outputs": [],
  35. "source": [
  36. "# Generate toy data\n",
  37. "np.random.seed(4321)\n",
  38. "n_samples = 1000"
  39. ]
  40. },
  41. {
  42. "cell_type": "markdown",
  43. "id": "84d8bc5e",
  44. "metadata": {},
  45. "source": [
  46. "machine learning algorithms need data close to 1 , this generated here, it is not needed to normalize data"
  47. ]
  48. },
  49. {
  50. "cell_type": "code",
  51. "execution_count": null,
  52. "id": "a1d437df",
  53. "metadata": {},
  54. "outputs": [],
  55. "source": [
  56. "class1_data = np.random.multivariate_normal([-1., -1.], [[1., 0.], [0., 1.]], n_samples)\n",
  57. "class2_data = np.random.multivariate_normal([1.0, 1.0], [[1., 0.], [0., 1.]], n_samples)"
  58. ]
  59. },
  60. {
  61. "cell_type": "code",
  62. "execution_count": null,
  63. "id": "6bbccf56",
  64. "metadata": {},
  65. "outputs": [],
  66. "source": [
  67. "# the data is merged together and the toy labels are asigned as [1, 0] and [0,1]\n",
  68. "train_data = np.concatenate([class1_data, class2_data])\n",
  69. "toy_labels = np.zeros(train_data.shape)\n",
  70. "toy_labels[:n_samples, 0] = 1\n",
  71. "toy_labels[n_samples:, 1] = 1"
  72. ]
  73. },
  74. {
  75. "cell_type": "code",
  76. "execution_count": null,
  77. "id": "f8dd0511",
  78. "metadata": {},
  79. "outputs": [],
  80. "source": [
  81. "# Plot the input data with points colored according to their labels\n",
  82. "plt.scatter(class1_data[:, 0], class1_data[:, 1], color='red')\n",
  83. "plt.scatter(class2_data[:, 0], class2_data[:, 1], color='blue')\n",
  84. "plt.title(\"Input data with points colored according to their labels\")\n",
  85. "plt.xlabel(\"Feature 1\")\n",
  86. "plt.ylabel(\"Feature 2\")\n",
  87. "plt.show()"
  88. ]
  89. },
  90. {
  91. "cell_type": "markdown",
  92. "id": "75fb1af9",
  93. "metadata": {},
  94. "source": [
  95. "Build a model, the sequential model is a linear stack of pre-made layers. In a Dense layer all neueral network layer is connected with all other layers. Here we have 32 nodes with input_shape 2 with means 2 dimensional data. The activation is 'relu' (rectified linear unit)\n",
  96. "Softmax maps the output of a model to probability distributions of the 2 classes. "
  97. ]
  98. },
  99. {
  100. "cell_type": "code",
  101. "execution_count": null,
  102. "id": "ad6dcef9",
  103. "metadata": {},
  104. "outputs": [],
  105. "source": [
  106. "model = tf.keras.models.Sequential([\n",
  107. " tf.keras.layers.Dense(32, activation='relu', input_shape=(2,)),\n",
  108. " tf.keras.layers.Dense(32, activation='relu'),\n",
  109. " tf.keras.layers.Dense(2, activation='softmax')\n",
  110. "])"
  111. ]
  112. },
  113. {
  114. "cell_type": "markdown",
  115. "id": "a9c38493",
  116. "metadata": {},
  117. "source": [
  118. "Adam optimizer is a gradient-based optimization algorithm for updating the weights in \n",
  119. "a neural network. The leanrning rate depends on the first and second moments of the \n",
  120. "gradients of the loss function with respect to the weights\n",
  121. "The loss function is BinaryCrossentropy since we have 2 classes of data\n",
  122. "The accuracy metric measures the percentage of instances where the model \n",
  123. "correctly predicted the class label and it can be computed as the number of correct\n",
  124. "predictions divided by the total number of instances in the test set."
  125. ]
  126. },
  127. {
  128. "cell_type": "code",
  129. "execution_count": null,
  130. "id": "7f6dc4ef",
  131. "metadata": {},
  132. "outputs": [],
  133. "source": [
  134. "model.compile(optimizer='adam',\n",
  135. "# loss=tf.keras.losses.CategoricalCrossentropy(),\n",
  136. " loss=tf.keras.losses.BinaryCrossentropy(),\n",
  137. " metrics=['accuracy'])"
  138. ]
  139. },
  140. {
  141. "cell_type": "markdown",
  142. "id": "a6397c0f",
  143. "metadata": {},
  144. "source": [
  145. "The object history contains loss and accuracy from the training process\n",
  146. "The model is trained by dividing the entire training data into smaller batches\n",
  147. "of a specified size, updating the model's parameters after each batch.\n",
  148. "The batch_size parameter determines the number of samples to be used in each batch. "
  149. ]
  150. },
  151. {
  152. "cell_type": "code",
  153. "execution_count": null,
  154. "id": "b98e46ba",
  155. "metadata": {},
  156. "outputs": [],
  157. "source": [
  158. "history = model.fit(train_data, toy_labels, epochs=20, batch_size=32, verbose=1)"
  159. ]
  160. },
  161. {
  162. "cell_type": "code",
  163. "execution_count": null,
  164. "id": "806497d2",
  165. "metadata": {},
  166. "outputs": [],
  167. "source": [
  168. "# Plot loss and accuracy\n",
  169. "plt.figure(figsize=(12, 4))\n",
  170. "\n",
  171. "plt.subplot(1, 2, 1)\n",
  172. "plt.plot(history.history['loss'])\n",
  173. "plt.title('Loss')\n",
  174. "plt.xlabel('Epoch')\n",
  175. "\n",
  176. "plt.subplot(1, 2, 2)\n",
  177. "plt.plot(history.history['accuracy'])\n",
  178. "plt.title('Accuracy')\n",
  179. "plt.xlabel('Epoch')\n",
  180. "\n",
  181. "plt.show()"
  182. ]
  183. },
  184. {
  185. "cell_type": "code",
  186. "execution_count": null,
  187. "id": "ca6da322",
  188. "metadata": {},
  189. "outputs": [],
  190. "source": [
  191. "# Plot data points and decision boundary\n",
  192. "x_min, x_max = train_data[:, 0].min() - .5, train_data[:, 0].max() + .5\n",
  193. "y_min, y_max = train_data[:, 1].min() - .5, train_data[:, 1].max() + .5\n",
  194. "xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))\n",
  195. "# creating a 2D grid from the arrays xx and yy which is the area of our inputs \n",
  196. "grid = np.c_[xx.ravel(), yy.ravel()]\n",
  197. "# get the predicted class probabilities for each data point in the grid.\n",
  198. "# The result Z is an array with shape (n_samples, n_classes) where n_samples\n",
  199. "# is the number of data points in the grid and n_classes is the number of\n",
  200. "# classes in the toy_labels. Z contains the predicted class probabilities\n",
  201. "# for each data point in the grid.\n",
  202. "Z = model.predict(grid)\n",
  203. "# The line Z = np.argmax(Z, axis=1) is used to convert the predicted probabilities\n",
  204. "# into class labels.\n",
  205. "Z = np.argmax(Z, axis=1)\n",
  206. "# reshaped Z variable is used to create the contour plot of the model's predictions \n",
  207. "# on the grid.\n",
  208. "Z = Z.reshape(xx.shape)\n"
  209. ]
  210. },
  211. {
  212. "cell_type": "code",
  213. "execution_count": null,
  214. "id": "54c02602",
  215. "metadata": {},
  216. "outputs": [],
  217. "source": [
  218. "plt.figure(figsize=(8, 8))\n",
  219. "plt.contourf(xx, yy, Z, cmap=plt.cm.RdBu, alpha=.8)\n",
  220. "plt.scatter(train_data[:, 0], train_data[:, 1], c=np.argmax(toy_labels, axis=1), cmap=plt.cm.RdBu)\n",
  221. "\n",
  222. "plt.show()"
  223. ]
  224. }
  225. ],
  226. "metadata": {
  227. "kernelspec": {
  228. "display_name": "Python 3 (ipykernel)",
  229. "language": "python",
  230. "name": "python3"
  231. },
  232. "language_info": {
  233. "codemirror_mode": {
  234. "name": "ipython",
  235. "version": 3
  236. },
  237. "file_extension": ".py",
  238. "mimetype": "text/x-python",
  239. "name": "python",
  240. "nbconvert_exporter": "python",
  241. "pygments_lexer": "ipython3",
  242. "version": "3.8.16"
  243. }
  244. },
  245. "nbformat": 4,
  246. "nbformat_minor": 5
  247. }