Rosenblatt感知器算法用python实现及结果
时间: 2024-03-25 12:36:26 浏览: 85
Python实现感知器算法
4星 · 用户满意度95%
Rosenblatt感知器算法是一种二元分类算法,它可以根据给定的训练数据集,学习到一个超平面,将数据集分为两个部分。
以下是用Python实现Rosenblatt感知器算法的代码和结果:
```
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.1, num_iterations=100):
self.learning_rate = learning_rate
self.num_iterations = num_iterations
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features + 1)
X = np.c_[X, np.ones(n_samples)]
for _ in range(self.num_iterations):
for i in range(n_samples):
if y[i] * np.dot(X[i], self.weights) <= 0:
self.weights += self.learning_rate * y[i] * X[i]
def predict(self, X):
n_samples, _ = X.shape
X = np.c_[X, np.ones(n_samples)]
y_pred = np.sign(np.dot(X, self.weights))
return y_pred
```
我们可以用以下代码测试这个算法:
```
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
X, y = make_blobs(n_samples=1000, centers=2, n_features=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
perceptron = Perceptron()
perceptron.fit(X_train, y_train)
y_pred = perceptron.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
```
输出结果为:
```
Accuracy: 1.0
```
可以看到,这个算法在这个数据集上取得了100%的准确率。
需要注意的是,Rosenblatt感知器算法只适用于线性可分的数据集。对于非线性可分的数据集,我们需要使用其他的分类算法。
阅读全文