{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "4ba31782", "metadata": {}, "outputs": [], "source": [ "import torch\n", "import numpy as np" ] }, { "cell_type": "markdown", "id": "83e63fc1", "metadata": {}, "source": [ "### " ] }, { "cell_type": "markdown", "id": "15a356a3", "metadata": {}, "source": [ "### 1b)\n", "Wenn `from_numpy` gemacht wird, teilen sich der tensor und numpy den gleichen Speicher, sonst ist es eine Kopie" ] }, { "cell_type": "markdown", "id": "c23b9d6f", "metadata": {}, "source": [ "### 1c)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1db0a783", "metadata": {}, "outputs": [], "source": [ "np.random.seed(1)\n", "rand_tensor = torch.rand((2,2,3))\n", "rand_tensor.numpy # gibt den Tensor als Numpy Array zurück\n", "rand_tensor.tolist # konvertiert tensor in Liste und schiebt ihn auf die CPU\n", "rand_tensor.item # funktioniert nur für einelementige Tensoren" ] }, { "cell_type": "code", "execution_count": null, "id": "11d1a2e1", "metadata": {}, "outputs": [], "source": [ "#1d)\n", "X = rand_tensor # Tensor\n", "print(X[:, -1]) # gibt alle Zeilen der letzten Spalte zurück\n", "print(X[...,-1]) # alle vorherigen Dimensionen \n", "XNP = np.array(np.random.random((2,2,3))) # Numpy Array\n", "print(XNP[:, -1]) # gibt alle Zeilen der letzten Spalte zurück\n", "print(XNP[...,-1])\n", "# ab zwei Dimensionen unterscheidet sich die Ausgabe" ] }, { "cell_type": "code", "execution_count": null, "id": "1d5f959d", "metadata": {}, "outputs": [], "source": [ "# 2b-d)\n", "from math import sin, pi\n", "def f(x,y):\n", " return x**2 + sin(y) +1\n", "# An Stelle u = (0,0) -> 1.0 v (1, pi/2) -> 3.0\n", "f(0,0)\n", "f(1,pi/2)\n", "# TODO selbst auf Papier partiell differenzieren\n", "x = torch.tensor([0.0,0.0],requires_grad=True)\n", "# x = torch.tensor([1.0,pi/2],requires_grad=True)\n", "fxy = x[0]**2 + sin(x[1]) +1\n", "fxy.backward()\n", "print(x.grad)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f2b8469b", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import nnwplot\n", "import matplotlib.pyplot as plt\n", "import copy\n", "import torch\n", "def ErrorRate(Y,T):\n", " if Y.ndim==1 or Y.shape[0]==1:\n", " errors=Y!=T\n", " return errors.sum()/Y.size\n", " else: # für mehrere Ausgaben in one-hot Kodierung:\n", " errors=Y.argmax(0)!=T.argmax(0)\n", " return errors.sum()/Y.shape[1]" ] }, { "cell_type": "code", "execution_count": null, "id": "1ef4b841", "metadata": {}, "outputs": [], "source": [ "class MLN:\n", " def __init__(self,dIn,hidden,cOut): # Konstruktor\n", " np.random.seed(42)\n", " self._b1=torch.tensor(np.zeros((hidden,1)), requires_grad=True)\n", " self._W1=torch.tensor(np.random.randn(hidden,dIn)/np.sqrt(dIn), requires_grad=True)\n", " self._b2=torch.tensor(np.zeros((cOut,1)), requires_grad=True)\n", " self._W2=torch.tensor(np.random.randn(cOut,hidden)/np.sqrt(hidden), requires_grad=True)\n", " if cOut==1:\n", " self.neuron=self.ythreshold\n", " else:\n", " self.neuron=self.ythresholdMult\n", " def net1(self,X):\n", " return self._W1 @ X + self._b1\n", " def z(self,X):\n", " return torch.tanh(self.net1(X))\n", " def net2(self,Z):\n", " return self._W2 @ Z + self._b2\n", " def y(self,X):\n", " return self.net2(self.z(X))\n", "\n", " def ythreshold(self, X):\n", " with torch.no_grad():\n", " return (self.y(torch.from_numpy(X)) >= 0).numpy()\n", " \n", " def onehot(self,T):\n", " e=np.identity(self._W2.shape[0])\n", " return e[:,T.astype(int)]\n", " def ythresholdMult(self, X):\n", " with torch.no_grad():\n", " idx = self.y(torch.from_numpy(X)).argmax(0).numpy()\n", " return self.onehot(idx)\n", " \n", " def DeltaTrain(self, X, T, eta, maxIter, maxErrorRate):\n", " bestError = 2;\n", " bestIt = 0; \n", " Xt = torch.from_numpy(X)\n", " Tt = torch.from_numpy(T) # nur für den Loss\n", " plt.ion() # interactive mode on\n", " for it in range(maxIter):\n", " Y = self.y(Xt)\n", " loss = 1/2 * ((Y-Tt)**2).mean()\n", " loss.backward()\n", " with torch.no_grad():\n", " self._W1.add_(-eta * self._W1.grad)\n", " self._b1.add_(-eta * self._b1.grad)\n", " self._W2.add_(-eta * self._W2.grad)\n", " self._b2.add_(-eta * self._b2.grad)\n", " self._W1.grad.zero_()\n", " self._b1.grad.zero_()\n", " self._W2.grad.zero_()\n", " self._b2.grad.zero_()\n", " err = ErrorRate(self.neuron(X), T)\n", " if (it%20) == 0:\n", " print('#{} err:{}\\n{}\\n{}\\n{}\\n{}'.format(it,err,self._W1,self._b1,self._W2,self._b2))\n", " nnwplot.plotTwoFeatures(X,T,self.neuron)\n", " #plt.pause(0.05) # warte auf GUI event loop: einkommentieren, falls Plot sich nicht ändert.\n", " if err < bestError:\n", " bestError = err\n", " bestIt = it\n", " bestParams = [p.detach().clone() for p in (self._W1, self._b1, self._W2, self._b2)]\n", " if err <= maxErrorRate:\n", " break\n", " with torch.no_grad():\n", " for p, b in zip((self._W1, self._b1, self._W2, self._b2), bestParams):\n", " p.copy_(b)\n", " print('#{} err:{}\\n{}\\n{}\\n{}\\n{}'.format(it,err,self._W1,self._b1,self._W2,self._b2))\n", " nnwplot.plotTwoFeatures(X,T,self.neuron)\n", " #plt.pause(0.05) # warte auf GUI event loop: einkommentieren, falls Plot sich nicht ändert.\n", " return bestError, bestIt\n" ] }, { "cell_type": "code", "execution_count": null, "id": "72da802f", "metadata": {}, "outputs": [], "source": [ "iris = np.loadtxt(\"../supplement_files/iris.csv\",delimiter=',')\n", "X=iris[:,0:4].T\n", "T=iris[:,4]\n", "T" ] }, { "cell_type": "code", "execution_count": null, "id": "82586be5", "metadata": {}, "outputs": [], "source": [ "plt.figure()\n", "slnIris = MLN(2,1,1) # HU: 1 und 5 gut, 2,3,8 schlecht\n", "slnIris.DeltaTrain(X[:2,0:100],T[0:100],0.2,2000,0.1)\n", "slnIris.neuron(X[:2,:])" ] }, { "cell_type": "code", "execution_count": null, "id": "f7b1de05", "metadata": {}, "outputs": [], "source": [ "plt.figure()\n", "slnIris = MLN(2,5,3)\n", "slnIris.DeltaTrain(X[2:4,:],slnIris.onehot(T),0.1,2000,0.04)\n", "slnIris.neuron(X[2:4,:]).argmax(0)\n" ] } ], "metadata": { "kernelspec": { "display_name": "nnw (3.14.0)", "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.14.0rc3" } }, "nbformat": 4, "nbformat_minor": 5 }