I am trying to use a perceptron in the Iris data set and implement a function to visualize the decision
boundaries but I get this ValueError: ‘red’ is not a valid color value.
I tried using color codes also .
the entire code I used so far is
`
import numpy as np
class Perceptron:
""" Perceptron classifier
Parameters
----------
eta:float
Learning rate(between 0.0 and 1.0)
n_iter:int
Passes over the training data set
random_state:int
Random generator sedd for random weight
initialization.
Attributes
----------
W_:1-darray
Weights after fitting
b_:Scalar
Bias unit after fitting
errors_: list
Number of misclassifications(updates) in each epoch.
"""
def __init__(self, eta=0.01, n_iter=50, random_state=1):
self.eta = eta
self.n_iter= n_iter
self.random_state=random_state
def fit(self,X,Y):
""" Fit training data.
Parameters
----------
X: {array-like}, shape = [n_examples, n_features]
Training vectors, where n_examples is the number of examples and n_features is the number of features.
y : array-like, shape = [n_examples]
Target values.
Returns
-------
self: object
"""
rgen=np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01,
size=X.shape[1])
self.b_=np.float_(0.)
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_ += update * xi
self.b_ += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def net_input(self, X):
""" Calculate net output """
return np.dot(X, self.w_) + self.b_
def predict(self, X):
""" Return class label after unit step """
return np.where(self.net_input(X) >= 0.0, 1, 0)
#Training on Iris dataset
import pandas as pd
from urllib.request import urlretrieve
s=' https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data '
df=pd.read_csv(s,header= None )
df.tail()
#select Setosa and versicolor
import matplotlib.pyplot as plt
import numpy as np
y=df.iloc[0:100, 4].values
y=np.where(y=='Iris-setosa',0,1)
#extract sepal lenght and petal lenght
X=df.iloc[0:100,[0,2]].values
#plot data
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 ='s', label='Versicolor')
plt.xlabel('Sepal lenght[cm]')
plt.ylabel('Petal lenght[cm]')
plt.legend(loc='upper left')
plt.show()`
the distribution of flower examples
`import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.colors import ListedColormap
def plot_decision_regions(X, y, classifier, resolution=0.02 ):
#setup marker generator and color map
markers=('o', 's', '^', 'v', '<')
colors = ('#FF0000', '#0000FF', '#90EE90', '#808080', '#00FFFF')
cmap= ListedColormap(colors[:len(np.unique(y))])
#plot the decision surface
x1_min, x1_max = X[:, 0].min()-1,X[:,0].max()+1
x2_min, x2_max = X[:,1].min()-1, X[:, 1].max()+1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x2_max, resolution),
np.arange(x2_min, x2_max, resolution))
lab=classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
lab=lab.reshape(xx1.shape)
plt.contourf(xx1, xx2, lab, alpha=0.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
#plot class exmples
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y==cl, 0],
y=X[y==cl, 1],
alpha=0.8,
c=colors[idx],
marker=markers[idx],
label=f'Class{cl}',
edgecolor='black')
`
And finally
plot_decision_regions(X, y, classifier=ppn)
plt.xlabel('Sepal lenght[cm]')
plt.ylabel('Petal lenght[cm]')
plt.legend(loc='upper left')
plt.show()
New contributor
samer abdullah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.