Neural networks can't multiply sequence by non-int of type 'float'
Hello, I need to implement a perceptron to linearly classify 2 species (Iris).
I've scoured the internet for solutions and can't get out of the problem
I took a code from the internet and tried to apply it to my csv just to see if it gave any result but as I'm a python beginner I don't know how to get around the situation. If anyone can give me a light I appreciate it.
import numpy as np
import pandas as pd
class Perceptron(object):
def __init__(self, eta=0.01, epochs=50):
self.eta = eta
self.epochs = epochs
def train(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.epochs):
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):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
df = pd.read_csv('/home/DIRETORIO/iris.csv', header=None)
# setosa and versicolor
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
# sepal length and petal length
X = df.iloc[0:100, [0,2]].values
%matplotlib inline
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_decision_regions
ppn = Perceptron(epochs=10, eta=0.1)
ppn.train(X, y)
print('Weights: %s' % ppn.w_)
plot_decision_regions(X, y, clf=ppn)
plt.title('Perceptron')
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.show()
plt.plot(range(1, len(ppn.errors_)+1), ppn.errors_, marker='o')
plt.xlabel('Iterations')
plt.ylabel('Misclassifications')
plt.show()
ERRO ERROR WHEN I TRY TO RUN ON JUPYTER (LINE 25) {
TypeError Traceback (most recent call
last)
<ipython-input-10-c97f88eafcb5> in <module>
5 ppn = Perceptron(epochs=10, eta=0.1)
6
----> 7 ppn.train(X, y)
8 print('Weights: %s' % ppn.w_)
9 plot_decision_regions(X, y, clf=ppn)
<ipython-input-8-7b4ff7d686b6> in train(self, X, y)
15 errors = 0
16 for xi, target in zip(X, y):
---> 17 update = self.eta * (target -
self.predict(xi))
18 self.w_[1:] += update * xi
19 self.w_[0] += update
<ipython-input-8-7b4ff7d686b6> in predict(self, X)
26
27 def predict(self, X):
---> 28 return np.where(self.net_input(X) >= 0.0, 1, -1)
<ipython-input-8-7b4ff7d686b6> in net_input(self, X)
23
24 def net_input(self, X):
---> 25 return np.dot(X, self.w_[1:]) + self.w_[0]
26
27 def predict(self, X):
TypeError: can't multiply sequence by non-int of type 'float'
1
1 answers
The problem is in the dataset, try using this one here: https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data .
The dataset you are trying to use has header and you put as parameter header=None.
Your code worked perfectly for me using the dataset from the link above.
0
Author: Bruno Mello, 2019-05-10 13:49:55