import matplotlib.pyplot as plt import numpy as np import nnwplot def error_rate(Y, T): if Y.ndim == 1 or Y.shape[0] == 1: errors = Y != T return errors.sum() / Y.size 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): self.dIn = dIn self.cOut = cOut np.random.seed(42) self._b = np.zeros((cOut, 1)) self._W = np.random.randn(dIn, cOut) / np.sqrt(dIn + 1) def neuron(self, X): net = self._W.T.dot(X) + self._b return net >= 0 def delta_train(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 = error_rate(Y, T) # if (it % 10) == 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 delta = T - Y self._W += X.dot(delta.T) * eta self._b += delta.sum() * eta 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)