python 感知器
时间: 2023-12-13 16:34:08 浏览: 44
感知器是一种二元线性分类器,它可以用来将一组输入数据分成两类。以下是一个简单的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 fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
y_ = np.where(y <= 0, -1, 1)
for _ in range(self.n_iterations):
for idx, x_i in enumerate(X):
linear_output = np.dot(x_i, self.weights) + self.bias
y_predicted = np.where(linear_output <= 0, -1, 1)
update = self.learning_rate * (y_[idx] - y_predicted)
self.weights += update * x_i
self.bias += update
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias
y_predicted = np.where(linear_output <= 0, -1, 1)
return y_predicted
```
这个感知器类包括了`fit`和`predict`方法。`fit`方法用于训练感知器,`predict`方法用于预测新的数据点的类别。下面是一个使用感知器进行二元分类的例子:
```python
X = np.array([[2, 3], [1, 2], [3, 4], [4, 5]])
y = np.array([1, -1, 1, -1])
perceptron = Perceptron()
perceptron.fit(X, y)
X_test = np.array([[1, 1], [5, 6]])
print(perceptron.predict(X_test)) # 输出:[-1, -1]
```
这个例子中,我们首先定义了一个包含4个数据点的训练集`X`和对应的标签`y`。然后我们创建了一个感知器对象,并使用`fit`方法对其进行训练。最后,我们使用`predict`方法对两个新的数据点进行分类,并输出了它们的类别。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)