利用感知机编程实现与非门功能测试
时间: 2023-05-16 16:05:27 浏览: 72
以下是利用感知机编程实现与非门功能测试的 Python 代码:
```python
import numpy as np
# 定义感知机类
class Perceptron:
def __init__(self, input_size):
self.weights = np.zeros(input_size + 1)
def predict(self, input):
summation = np.dot(input, self.weights[1:]) + self.weights[0]
return 1 if summation > 0 else 0
def train(self, input, target, learning_rate=0.1, epochs=100):
for _ in range(epochs):
for i in range(len(input)):
prediction = self.predict(input[i])
self.weights[1:] += learning_rate * (target[i] - prediction) * input[i]
self.weights[0] += learning_rate * (target[i] - prediction)
# 定义与非门的输入和输出
input = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
target = np.array([1, 1, 1, 0])
# 创建感知机对象并训练
perceptron = Perceptron(2)
perceptron.train(input, target)
# 测试感知机是否成功实现与非门功能
print("0 AND 0 = ", perceptron.predict(np.array([0, 0])))
print("0 AND 1 = ", perceptron.predict(np.array([0, 1])))
print("1 AND 0 = ", perceptron.predict(np.array([1, 0])))
print("1 AND 1 = ", perceptron.predict(np.array([1, 1])))
```
以上代码可以成功实现与非门功能测试。