Skip to content

I came across some issues in Chapter 01. Errors occurred when I ran the code. #2

@marcelotiziano

Description

@marcelotiziano

When I ran the code:
from matplotlib.colors import ListedColormap

Thanks to Sebastian Raschka for 'plot_decision_regions' function

def plot_decision_regions(X, y, classifier, resolution=0.02):

# setup marker generator and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
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, x1_max, resolution),
                     np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())

# plot class samples
for idx, cl in enumerate(np.unique(y)):
    plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
                alpha=0.8, c=cmap(idx),
                marker=markers[idx], label=cl)

from sklearn.linear_model import perceptron

from sklearn.datasets import make_classification
X, y = make_classification(30, 2, 2, 0, weights=[.3, .3], random_state=300)

plt.scatter(X[:,0], X[:,1], s=50)

pct = perceptron.Perceptron(max_iter=100, verbose=0, random_state=300, fit_intercept=True, eta0=0.002)
pct.fit(X, y)

plot_decision_regions(X, y, classifier=pct)
plt.title('Perceptron')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

The following error occurred.:
ImportError Traceback (most recent call last)
Cell In[17], line 28
23 for idx, cl in enumerate(np.unique(y)):
24 plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
25 alpha=0.8, c=cmap(idx),
26 marker=markers[idx], label=cl)
---> 28 from sklearn.linear_model import perceptron
30 from sklearn.datasets import make_classification
31 X, y = make_classification(30, 2, 2, 0, weights=[.3, .3], random_state=300)

ImportError: cannot import name 'perceptron' from 'sklearn.linear_model'

Then, I update the line "from sklearn.linear_model import perceptron"
to "from sklearn.linear_model import Perceptron"

And the line "X, y = make_classification(30, 2, 2, 0, weights=[.3, .3], random_state=300)"
to "# Generate synthetic dataset
X, y = make_classification(
n_samples=30, # Total number of samples
n_features=2, # Number of features
n_informative=2, # Number of informative features
n_redundant=0, # Number of redundant features
weights=[0.3, 0.7], # Class weights
random_state=300 # Random seed for reproducibility
)"

After fixing these issues, the code worked properly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions