感知器 python
时间: 2023-10-19 14:34:43 浏览: 46
感知器是一种简单的机器学习算法,用于二分类任务。在 Python 中,我们可以使用 numpy 库来实现感知器。
以下是一个简单的感知器实现示例:
```python
import numpy as np
class Perceptron:
def __init__(self, num_features):
self.weights = np.zeros(num_features)
self.bias = 0
def predict(self, x):
activation = np.dot(self.weights, x) + self.bias
return 1 if activation >= 0 else 0
def train(self, X, y, learning_rate=0.1, epochs=100):
for _ in range(epochs):
for i in range(len(X)):
prediction = self.predict(X[i])
error = y[i] - prediction
self.weights += learning_rate * error * X[i]
self.bias += learning_rate * error
```
在上述代码中,`Perceptron` 类初始化权重和偏差为零,并且具有 `predict` 方法用于预测输入的类别。`train` 方法用于训练感知器,其中 `X` 是训练样本的特征向量,`y` 是对应的目标标签。
你可以使用以下代码进行测试:
```python
X = np.array([[2, 4], [4, 5], [1, 3], [6, 4]])
y = np.array([0, 0, 0, 1])
perceptron = Perceptron(num_features=2)
perceptron.train(X, y)
test_samples = np.array([[5, 3], [2, 2]])
for sample in test_samples:
prediction = perceptron.predict(sample)
print(f"Input: {sample}, Prediction: {prediction}")
```
上述代码中,我们定义了一个简单的二分类问题,`X` 是特征向量,`y` 是对应的目标标签。我们创建了一个 `Perceptron` 实例,并使用 `train` 方法对其进行训练。然后,我们使用 `predict` 方法对测试样本进行预测,并打印预测结果。
希望能帮到你!如果有任何问题,请随时问。