编写用感知准则函数判别方法对二维数据进行分类的通用函数
时间: 2023-12-23 22:02:36 浏览: 25
以下是使用感知准则函数对二维数据进行分类的 Python 代码示例:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.1, epochs=100):
self.learning_rate = learning_rate
self.epochs = epochs
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
# 初始化权重和偏置
self.weights = np.zeros(n_features)
self.bias = 0
# 迭代训练
for _ in range(self.epochs):
for i in range(n_samples):
# 计算感知准则函数的值
pred = np.dot(self.weights, X[i]) + self.bias
if y[i] * pred <= 0:
# 更新权重和偏置
self.weights += self.learning_rate * y[i] * X[i]
self.bias += self.learning_rate * y[i]
def predict(self, X):
# 计算感知准则函数的值
pred = np.dot(X, self.weights) + self.bias
# 返回分类结果
return np.where(pred >= 0, 1, -1)
```
使用方法:
```python
X = np.array([[2, 1], [3, 2], [4, 3], [1, 2], [2, 3], [3, 4]])
y = np.array([1, 1, 1, -1, -1, -1])
clf = Perceptron()
clf.fit(X, y)
print(clf.predict(np.array([[5, 4], [2, 2]]))) # [-1, 1]