线性感知器学习算法python代码
时间: 2024-04-24 22:18:39 浏览: 25
线性感知器学习算法是一种二分类的机器学习算法,它可以用于将输入数据分为两个类别。以下是一个简单的线性感知器学习算法的Python代码示例:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, num_iterations=1000):
self.learning_rate = learning_rate
self.num_iterations = num_iterations
def train(self, X, y):
self.weights = np.zeros(X.shape)
self.bias = 0
for _ in range(self.num_iterations):
for i in range(X.shape):
prediction = self.predict(X[i])
update = self.learning_rate * (y[i] - prediction)
self.weights += update * X[i]
self.bias += update
def predict(self, X):
activation = np.dot(X, self.weights) + self.bias
return np.where(activation >= 0, 1, -1)
```
使用示例:
```python
# 创建一个Perceptron对象
perceptron = Perceptron(learning_rate=0.1, num_iterations=100)
# 训练数据
X_train = np.array([[2, 3], [4, 5], [1, 2], [6, 7]])
y_train = np.array([1, 1, -1, -1])
perceptron.train(X_train, y_train)
# 预测新数据
X_test = np.array([[3, 4], [5, 6]])
predictions = perceptron.predict(X_test)
print(predictions)
```
这段代码实现了一个简单的线性感知器学习算法,其中`train`方法用于训练模型,`predict`方法用于预测新数据。在训练过程中,通过更新权重和偏置来逐步调整模型以适应训练数据。最后,使用训练好的模型对新数据进行预测,并输出预测结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)