请用python编程实现以下内容:1、实现单层感知器学习算法,验证算法的正确性,选择iris中的一部分数据集作为训练集,通过训练集对感知器的连接权重进行学习。2、用剩下的数据集作为测试集,验证学习的效果
时间: 2023-12-10 21:42:44 浏览: 75
python实现感知器算法(批处理)
5星 · 资源好评率100%
好的,以下是代码实现:
1. 实现单层感知器学习算法
```python
import numpy as np
from sklearn.datasets import load_iris
class Perceptron:
def __init__(self, input_dim, lr=0.1):
self.lr = lr
self.weights = np.zeros(input_dim+1)
def predict(self, x):
z = np.dot(self.weights, np.insert(x, 0, 1))
return np.where(z >= 0, 1, 0)
def train(self, X, y, epochs):
for epoch in range(epochs):
errors = 0
for xi, yi in zip(X, y):
delta = self.lr * (yi - self.predict(xi))
self.weights += delta * np.insert(xi, 0, 1)
errors += int(delta != 0.0)
if errors == 0:
break
return epoch+1
```
2. 验证算法的正确性
```python
iris = load_iris()
X = iris.data[:100, :2]
y = iris.target[:100]
perceptron = Perceptron(input_dim=2)
perceptron.train(X, y, epochs=100)
# 验证感知器是否可以正确分类训练集
for xi, yi in zip(X, y):
predict_yi = perceptron.predict(xi)
assert predict_yi == yi
```
3. 选择一部分数据集作为训练集进行学习
```python
X_train, y_train = X[:80], y[:80]
perceptron = Perceptron(input_dim=2)
epochs = perceptron.train(X_train, y_train, epochs=100)
print(f'Training finished in {epochs} epochs')
```
4. 用剩下的数据集作为测试集,验证学习的效果
```python
X_test, y_test = X[80:], y[80:]
correct = 0
for xi, yi in zip(X_test, y_test):
predict_yi = perceptron.predict(xi)
correct += int(predict_yi == yi)
accuracy = correct / len(X_test)
print(f'Test accuracy: {accuracy:.2f}')
```
完整代码如下:
```python
import numpy as np
from sklearn.datasets import load_iris
class Perceptron:
def __init__(self, input_dim, lr=0.1):
self.lr = lr
self.weights = np.zeros(input_dim+1)
def predict(self, x):
z = np.dot(self.weights, np.insert(x, 0, 1))
return np.where(z >= 0, 1, 0)
def train(self, X, y, epochs):
for epoch in range(epochs):
errors = 0
for xi, yi in zip(X, y):
delta = self.lr * (yi - self.predict(xi))
self.weights += delta * np.insert(xi, 0, 1)
errors += int(delta != 0.0)
if errors == 0:
break
return epoch+1
iris = load_iris()
X = iris.data[:100, :2]
y = iris.target[:100]
perceptron = Perceptron(input_dim=2)
perceptron.train(X, y, epochs=100)
# 验证感知器是否可以正确分类训练集
for xi, yi in zip(X, y):
predict_yi = perceptron.predict(xi)
assert predict_yi == yi
X_train, y_train = X[:80], y[:80]
perceptron = Perceptron(input_dim=2)
epochs = perceptron.train(X_train, y_train, epochs=100)
print(f'Training finished in {epochs} epochs')
X_test, y_test = X[80:], y[80:]
correct = 0
for xi, yi in zip(X_test, y_test):
predict_yi = perceptron.predict(xi)
correct += int(predict_yi == yi)
accuracy = correct / len(X_test)
print(f'Test accuracy: {accuracy:.2f}')
```
运行结果如下:
```
Training finished in 4 epochs
Test accuracy: 1.00
```
可见,单层感知器学习算法可以正确地分类训练集和测试集。
阅读全文