# -*- coding: utf-8 -*-
import numpy as np
from sklearn.datasets import load_iris
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
#%%
def plot_decision_regions(model, X, y, resolution=0.02):
"param resolution:分辨率"
# initialization colors map
colors = ['red', 'blue']
markers = ['o', 'x']
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision regions
x1_max, x1_min = max(X[:, 0]) + 1, min(X[:, 0]) - 1
x2_max, x2_min = max(X[:, 1]) + 1, min(X[:, 1]) - 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
Z = model.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)
plt.show()
#%%
class PerceptronBase(object):
def __init__(self, eta=0.1, n_iter=50):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w = np.zeros(X.shape[1])
self.b = 0
self.errors_ = []
for epo in range(self.n_iter):
errors = 0
for xi, yi in zip(X, y):
update = self.eta * (yi - self.predict(xi))
self.w += update * xi
self.b += update
errors += int(update != 0.0)
if errors == 0:
break
self.errors_.append(errors)
print('Finish training after {} epoch !!'.format(epo))
def sign(self, xi):
return np.dot(xi, self.w) + self.b
def predict(self, xi):
return np.where(self.sign(xi) > 0.0, 1, -1)
#%%
iris = load_iris()
X = iris.data[:100, [0, 2]]
y = iris.target[:100]
#%%
X, y = make_blobs(n_samples=1000, centers=2)
#%%
y = np.where(y == 1, 1, -1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
ppn = PerceptronBase(eta=0.9, n_iter=100)
ppn.fit(X_train, y_train)
plot_decision_regions(ppn, X_train, y_train.reshape(-1,))
感知机
最新推荐文章于 2025-03-07 21:58:16 发布