燕尾花感知机机学习python程序
时间: 2023-10-16 19:07:17 浏览: 50
以下是使用Python实现燕尾花感知机的简单示例代码:
```python
import numpy as np
class Perceptron:
def __init__(self, lr=0.01, epochs=1000):
self.lr = lr
self.epochs = epochs
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.epochs):
for i in range(n_samples):
z = np.dot(self.weights, X[i]) + self.bias
y_pred = np.where(z > 0, 1, 0)
self.weights += self.lr * (y[i] - y_pred) * X[i]
self.bias += self.lr * (y[i] - y_pred)
def predict(self, X):
z = np.dot(X, self.weights) + self.bias
y_pred = np.where(z > 0, 1, 0)
return y_pred
```
在这个示例中,我们使用了NumPy库来进行向量化计算,Perceptron类包含了fit和predict方法。fit方法用于训练模型,而predict方法用于对新数据进行预测。
我们可以使用sklearn库中的load_iris函数来加载燕尾花数据集,然后使用上述代码对数据进行训练和测试,示例如下:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载燕尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将类别0和类别1作为正样本,类别2作为负样本
X = X[:100]
y = y[:100]
y[y == 0] = -1
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 训练模型
model = Perceptron(lr=0.1, epochs=100)
model.fit(X_train, y_train)
# 测试模型
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
在这个示例中,我们将类别0和类别1作为正样本,类别2作为负样本,然后划分训练集和测试集。我们使用Perceptron类对训练集进行训练,并对测试集进行预测,最后计算模型的准确率。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)