感知机分类 python
时间: 2023-10-08 07:06:50 浏览: 83
以下是一个简单的感知机分类器的 Python 代码示例:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
def train(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.n_iterations):
for i in range(n_samples):
if y[i] * self.predict(X[i]) <= 0:
self.weights += self.learning_rate * y[i] * X[i]
self.bias += self.learning_rate * y[i]
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return np.where(linear_output >= 0, 1, -1)
```
使用该代码可以训练一个二元分类器。下面是一个使用示例:
```python
X_train = np.array([[1, 2], [2, 1], [3, 3], [4, 3]])
y_train = np.array([1, 1, -1, -1])
classifier = Perceptron()
classifier.train(X_train, y_train)
X_test = np.array([[1, 1], [4, 4], [5, 5]])
print(classifier.predict(X_test)) # 输出 [1, -1, -1]
```
在上述示例中,我们首先使用四个样本和它们的标签进行训练。然后,我们使用训练好的分类器来预测三个测试样本的类别。
阅读全文