NNW/Lösungen_N/SLN_Blatt2.py

65 lines
2.1 KiB
Python

# -*- coding: utf-8 -*-
# %%
import numpy as np
import nnwplot
import matplotlib.pyplot as plt
# %% ErrorRate
def ErrorRate(Y,T):
if Y.ndim==1 or Y.shape[0]==1:
errors=Y!=T # gibt boolsche Liste zurück
return errors.sum()/Y.size # summiert True als 1 in errors auf
else: # für mehrere Ausgaben in one-hot Kodierung:
errors=Y.argmax(0)!=T.argmax(0)
return errors.sum()/Y.shape[1]
# %%
class SLN:
def __init__(self, dIn, cOut): # Konstruktor
np.random.seed(42)
self._b=np.zeros((cOut,1))
self._W=np.random.randn(cOut,dIn)/np.sqrt(dIn+1)
def neuron(self, X):
N = X.shape[1]
net = np.zeros(N)
net = self._W @ X
# b verwenden ...
net = net - self._b
return net > 0 # threshold ....
def DeltaTrain(self, X, T, eta, maxIter, maxErrorRate):
N=X.shape[1] # Anzahl Trainingsdaten
plt.ion() # interactive mode on
for it in range(maxIter):
Y = self.neuron(X) # nur ein Aufruf
err = ErrorRate(Y, T)
if (it%20) == 0:
print('#{} err:{}\n{}\n{}'.format(it,err,self._W,self._b))
nnwplot.plotTwoFeatures(X, T, self.neuron)
plt.pause(0.05) # warte auf GUI event loop (je nach python Version notwendig oder nicht)
if err <= maxErrorRate:
break
Y = Y.astype(float)
# update _W
# X.shape = (2,4), T.shape = (1,4), Y.shape = (1,4)
self._W += eta * (T - Y) @ X.T / N
# update _b
self._b -= eta * (T - Y) @ np.ones((1,N)).T / N
print('#{} err:{}\n{}\n{}'.format(it,err,self._W,self._b))
nnwplot.plotTwoFeatures(X, T, self.neuron)
plt.pause(0.05) # warte auf GUI event loop (je nach python Version notwendig oder nicht)
input("Press Enter to continue...") # wenn gewünscht ...
# %%
# 3f)
X_AND = np.array([[0,0], [1,0], [0,1], [1,1]]).T
T_AND = np.array([[0],[0],[0],[1]]).T
sln = SLN(2, 1)
sln.DeltaTrain(X_AND, T_AND,0.5,10,0)
# %%