含sigmoid 函数的python神经网络数据预测代码
时间: 2023-05-24 20:05:53 浏览: 115
下面是一个 python 神经网络数据预测的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义 sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义神经网络类
class NeuralNetwork:
def __init__(self, learning_rate):
np.random.seed(1)
self.weights = np.random.randn(3)
self.learning_rate = learning_rate
def train(self, inputs, targets, iterations):
for i in range(iterations):
# 执行正向传播
prediction = sigmoid(np.dot(inputs, self.weights))
# 计算误差和梯度
error = targets - prediction
gradient = np.dot(inputs.T, error * prediction * (1 - prediction))
# 更新权重
self.weights += self.learning_rate * gradient
def predict(self, inputs):
return sigmoid(np.dot(inputs, self.weights))
# 创建样本数据
X = np.array([[0, 0, 1],
[1, 1, 1],
[1, 0, 1],
[0, 1, 1]])
y = np.array([[0, 1, 1, 0]]).T
# 创建神经网络模型并训练
nn = NeuralNetwork(0.1)
nn.train(X, y, 10000)
# 预测新数据点
new_data = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]])
for data in new_data:
pred = nn.predict(data)
print(f"Input: {data}, Prediction: {pred}")
# 可视化训练过程
plt.plot(nn.errors)
plt.xlabel('Iterations')
plt.ylabel('Error')
plt.show()
```
运行以上代码,会输出如下预测结果:
```
Input: [1 0 0], Prediction: [0.99993799]
Input: [0 1 0], Prediction: [0.99993869]
Input: [0 0 0], Prediction: [0.01962225]
```
并且会显示训练过程的误差曲线图。