Search code examples
pythonperceptron

Perceptron with python - TypeError appears but why?


I am trying to code a Perceptron algorithm in python3. I am following a book example from Sebastian Raschka. His code can be found here:(https://github.com/rasbt/python-machine-learning-book-2nd-edition).

Unfortunately I can not figure out why the error: TypeError: object() takes no parameters appears and how to handle it.

I have used PyCharm first and now I am testing that issue with Jupiter step by step. I have even copied the fully code example from the GitHub repository offered from S. Raschka. But even than I get the same error, which is actually confusing me, because it means its probably not just a typo.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap


class Perceptron(object):
    """ Perzeptron Klassifizierer

Parameter
---------
eta : float
    Lernrate (zwischen 0.0 und 1.0)
n_iter : int
    Durchläufe der Trainningsdatenmenge

Attribute
---------
w_ : 1d-array
    Gewichtugen nach Anpassungen
errors_ : list
    Anzahl der Fehlerklassifizerungen pro Epoche

"""


def __init__(self, eta=0.01, n_iter=10):
    self.eta = eta
    self.n_iter = n_iter


def fit(self, X, y):
""" Anpassungen and die Trainingsdaten

Parameter
---------
X : {array-like}, shape = [n_samples, n_features]
    Trainingsvektoren, n_samples ist
    die Anzahl der Objekte und
    n_features ist die Anzahl der Merkmale
y : array-like, shape = [n_samples]
    Zielwerte

Rückgabewert
------------
self : object

"""
    self.w_ = np.zeros(1 + X.shape[1])
    self.errors_ = []

    for _ in range(self.n_iter):
        errors = 0
        for xi, target in zip(X, y):
            update = self.eta * (target - self.predict(xi))
            self.w_[1:] += update * xi
            self.w_[0] += update
            errors += int(update != 0.0)
        self.errors_.append(errors)
        return self

    def net_input(self, X):
    """ Nettoeingabe berechnen"""
    return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
    """Klassenbezeichnung zurückgeben"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-    databases/iris/iris.data', header=None)

df.tail()

# Expected result:
# A table with given numbers will be shown
# Now we are plotting everything and will see a given chart:

y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
X = df.iloc[0:100, [0, 2]].values

plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o',     label='setosa')
plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x',   label='versicolor')
plt.xlabel('Länge des Kelchblatts [cm]')
plt.ylabel('Länge des Blütenblatts [cm]')
plt.legend(loc='upper left')
plt.show()

#Error appears here:

ppn = Perceptron(eta=0.1, n_iter=10)
ppn.fit(X, y)
plt.plot(range(1, len(ppn.errors_) + 1), ppn_errors_,
         marker='o')
plt.xlabel('Epochen')
plt.ylabel('Anzahl der Updates')
plt.show()

The given Error tells me the following"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call >>last)
<ipython-input-29-abc085daeef7> in <module>
----> 1 ppn = Perceptron(eta=0.1, n_iter=10)
      2 ppn.fit(X, y)
      3 plt.plot(range(1, len(ppn.errors_) + 1), ppn_errors_,
      4          marker='o')
      5 plt.xlabel('Epochen')

TypeError: object() takes no parameters
------------------------------------------------------------------------

As shown above, the code is working until the last few lines and depends on the part with "ppn = Perceptron(eta...) etc." I expected another plot, a diagram, with the amount of false classifiers in opposite to the amount of epochs. Did I forget any library? I just don't get it... Thanks a lot


Solution

  • You defined the class Perzeptron but create an instance of Perceptron (c instead of z). It seems like you defined Perceptron earlier in your ipython session without defining the __init__ method taking two arguments.