基于神经网络的鸢尾花分类代码
时间: 2023-11-14 12:14:52 浏览: 93
您好,以下是一个基于神经网络的鸢尾花分类代码,供您参考:
```python
import numpy as np
# sigmoid 激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# sigmoid 函数的导数
def sigmoid_derivative(x):
return x * (1 - x)
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_shape, output_shape, hidden_shape=4):
self.input_shape = input_shape
self.hidden_shape = hidden_shape
self.output_shape = output_shape
# 权重初始化为随机值
self.weights1 = np.random.randn(self.input_shape, self.hidden_shape)
self.weights2 = np.random.randn(self.hidden_shape, self.output_shape)
# 前向传播
def feed_forward(self, X):
# 输入层到隐藏层
self.hidden_layer = sigmoid(np.dot(X, self.weights1))
# 隐藏层到输出层
self.output_layer = sigmoid(np.dot(self.hidden_layer, self.weights2))
# 反向传播
def backpropagation(self, X, y, learning_rate):
# 计算输出层误差
output_error = y - self.output_layer
output_delta = output_error * sigmoid_derivative(self.output_layer)
# 计算隐藏层误差
hidden_error = np.dot(output_delta, self.weights2.T)
hidden_delta = hidden_error * sigmoid_derivative(self.hidden_layer)
# 更新权重
self.weights2 += learning_rate * np.dot(self.hidden_layer.T, output_delta)
self.weights1 += learning_rate * np.dot(X.T, hidden_delta)
# 训练模型
def train(self, X, y, learning_rate, num_epochs):
for i in range(num_epochs):
self.feed_forward(X)
self.backpropagation(X, y, learning_rate)
# 预测结果
def predict(self, X):
self.feed_forward(X)
return self.output_layer
```
希望以上代码对您有帮助!
阅读全文