神经网络模型python示例
时间: 2023-07-25 13:48:40 浏览: 44
神经网络是机器学习中常用的一种模型,它可以通过学习输入和输出之间的关系,来预测新的数据的输出。以下是一个简单的神经网络模型的Python示例:
```
import numpy as np
# 定义神经网络模型
class NeuralNetwork():
def __init__(self):
# 随机初始化权重
self.weights = 2 * np.random.random((3, 1)) - 1
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def train(self, inputs, outputs, iterations):
for i in range(iterations):
# 前向传播
output = self.predict(inputs)
# 计算误差
error = outputs - output
# 反向传播
adjustment = np.dot(inputs.T, error * self.sigmoid_derivative(output))
self.weights += adjustment
def predict(self, inputs):
inputs = inputs.astype(float)
output = self.sigmoid(np.dot(inputs, self.weights))
return output
# 训练数据
training_inputs = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_outputs = np.array([[0, 1, 1, 0]]).T
# 创建神经网络
neural_network = NeuralNetwork()
# 训练神经网络
neural_network.train(training_inputs, training_outputs, 10000)
# 预测新的数据
new_data = np.array([1, 0, 0])
prediction = neural_network.predict(new_data)
print(prediction)
```
在上面的示例中,我们定义了一个简单的神经网络模型,并使用随机初始化的权重进行训练。我们使用sigmoid函数作为激活函数,并使用梯度下降算法进行反向传播来更新权重。最后,我们使用训练好的神经网络来预测新的数据的输出。