编写一个基于梯度下降法的感知器二分类代码
时间: 2023-05-15 07:05:19 浏览: 57
以下是一个基于梯度下降法的感知器二分类代码的示例:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.1, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
def fit(self, X, y):
n_samples, n_features = X.shape
# Initialize weights and bias
self.weights = np.zeros(n_features)
self.bias = 0
# Gradient descent
for _ in range(self.n_iterations):
for i in range(n_samples):
# Compute the predicted output
y_pred = self.predict(X[i])
# Update the weights and bias
self.weights += self.learning_rate * (y[i] - y_pred) * X[i]
self.bias += self.learning_rate * (y[i] - y_pred)
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias
return np.where(linear_output >= 0, 1, -1)
```
这个感知器可以用来解决二分类问题。它使用梯度下降法来更新权重和偏置,以最小化损失函数。在每次迭代中,它遍历所有的样本,并根据预测值和真实值之间的差异来更新权重和偏置。最终,它可以用来预测新的样本的类别。