You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
HI...Im trying to run the perceptron model in Pycharm professional and I keep getting the error below:
Traceback (most recent call last):
File "C:\Users\skwon\PycharmProjects\pythonProject1\iris_ds_&plot_Perceptron_10052023.py", line 87, in
ppn.fit(X, y)
File "C:\Users\skwon\PycharmProjects\pythonProject1\iris_ds&_plot_Perceptron_10052023.py", line 70, in fit
Update = self.eta * (target - self.predict(xi))
~~~~~~~^~~~~~~~~~~~~~~~~~
numpy.core._exceptions._UFuncNoLoopError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U11'), dtype('int32')) -> None
Below is the Perceptron model which I ran both originally and then modified slightly for simlicity. I keep getting the same error. Any insights or help would be appreciated!
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
class Perceptron(object):
"""Perceptron classifier.
Parameters
-----------
eta : float
Learning Rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
shuffle : bool (default: True)
Shuffles training data every epoch if True to prevent cycles.
random_state : int (default: None)
set random state for shuffing and initialize the weights.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
errors_ : list
Number of misclassifications (updates) in each epoch.
"""
def _init_(self, eta=0.01, n_iter=10, shuffle=True, random_state=None, random_seed=1):
self.eta = eta
self.n_iter = n_iter
self.shuffle = shuffle
self.random_seed = random_seed
np.random_seed(random_state)
def fit(self, X, y):
"""Fit training data.
Parameters
----------
X : {array-like}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
"""
rgen = np.random.RandomState(self.random_seed)
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
if self.shuttle:
X, y = self_shuffle(X, y)
errors = 0
for xi.target in zip(X, y):
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 _shuffle(self, X, y):
"""Shuffle training data"""
r = np.random.permutation(len(y))
return X[r], y[r]
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.net_input(X) >= 0.0, 1, -1)
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('Epochs')
plt.ylabel('Number of updates')
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
HI...Im trying to run the perceptron model in Pycharm professional and I keep getting the error below:
Traceback (most recent call last):
File "C:\Users\skwon\PycharmProjects\pythonProject1\iris_ds_&plot_Perceptron_10052023.py", line 87, in
ppn.fit(X, y)
File "C:\Users\skwon\PycharmProjects\pythonProject1\iris_ds&_plot_Perceptron_10052023.py", line 70, in fit
Update = self.eta * (target - self.predict(xi))
~~~~~~~^~~~~~~~~~~~~~~~~~
numpy.core._exceptions._UFuncNoLoopError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U11'), dtype('int32')) -> None
Below is the Perceptron model which I ran both originally and then modified slightly for simlicity. I keep getting the same error. Any insights or help would be appreciated!
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
'machine-learning-databases/iris/iris.data', header=None)
print(df)
select sertosa and versicolor
y = df.iloc[0:100, 4].values
x = np.where(y == 'Iris-setosa', -1, 1)
extract sepal length and petol length
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='x', label='versicolor')
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')
plt.tight_layout()
#plt.savefig('./images/02_06.png', dpe=300)
plt.show()
Perceptron
class Perceptron(object):
"""Perceptron classifier.
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('Epochs')
plt.ylabel('Number of updates')
plt.tight_layout()
plt.savefig('./perceptron_1.png', dpi=300)
plt.show()
Beta Was this translation helpful? Give feedback.
All reactions