感知器分类算法用python呈现出来4个案例
时间: 2024-03-26 18:34:15 浏览: 16
以下是四个使用感知器分类算法的Python案例:
1. Iris数据集分类
```
from sklearn.datasets import load_iris
import numpy as np
# 加载Iris数据集
iris = load_iris()
# 取出前两个特征和对应标签
X = iris.data[:, :2]
y = (iris.target != 0) * 1
# 定义感知器类
class Perceptron:
def __init__(self):
self.w = None
self.b = None
def model(self, x):
return 1 if (np.dot(self.w, x) >= self.b) else 0
def predict(self, X):
y_pred = []
for x in X:
result = self.model(x)
y_pred.append(result)
return np.array(y_pred)
def fit(self, X, y, epochs=1):
self.w = np.zeros(X.shape[1])
self.b = 0
for _ in range(epochs):
for x, y_true in zip(X, y):
y_pred = self.model(x)
if y_true == 1 and y_pred == 0:
self.w += x
self.b += 1
elif y_true == 0 and y_pred == 1:
self.w -= x
self.b -= 1
# 训练模型
perceptron = Perceptron()
perceptron.fit(X, y)
# 可视化分类结果
import matplotlib.pyplot as plt
plt.scatter(X[:,0], X[:,1], c=y)
line_x = np.arange(4, 8.1, 0.1)
line_y = (-perceptron.w[0]*line_x - perceptron.b) / perceptron.w[1]
plt.plot(line_x, line_y, 'k-')
plt.show()
```
2. 鸢尾花数据集二分类
```
from sklearn.datasets import load_iris
from sklearn.linear_model import Perceptron
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载Iris数据集
iris = load_iris()
# 取出前两个特征和对应标签
X = iris.data[:, :2]
y = (iris.target != 0) * 1
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
model = Perceptron()
model.fit(X_train, y_train)
# 预测测试集
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
3. MNIST数据集分类
```
from sklearn.datasets import fetch_openml
from sklearn.linear_model import Perceptron
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载MNIST数据集
mnist = fetch_openml('mnist_784')
# 取出前10000个样本和对应标签
X = mnist.data[:10000] / 255.0 # 归一化
y = mnist.target[:10000].astype(int)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
model = Perceptron()
model.fit(X_train, y_train)
# 预测测试集
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
4. 鸢尾花数据集多分类
```
from sklearn.datasets import load_iris
from sklearn.linear_model import Perceptron
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载Iris数据集
iris = load_iris()
# 取出前两个特征和对应标签
X = iris.data[:, :2]
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
model = Perceptron(multi_class='ovr')
model.fit(X_train, y_train)
# 预测测试集
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```