python建立神经网络代码
时间: 2023-06-16 21:04:57 浏览: 145
以下是一个基本的Python代码示例,用于建立一个简单的神经网络:
```python
import numpy as np
# 设置随机种子以保证每次运行结果一致
np.random.seed(0)
# 定义神经网络结构
input_neurons = 3
hidden_neurons = 4
output_neurons = 2
# 初始化权重
weights_input_hidden = np.random.randn(input_neurons, hidden_neurons)
weights_hidden_output = np.random.randn(hidden_neurons, output_neurons)
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义前向传输函数
def forward(x):
hidden_input = np.dot(x, weights_input_hidden)
hidden_output = sigmoid(hidden_input)
output = np.dot(hidden_output, weights_hidden_output)
return sigmoid(output)
# 测试前向传输函数
x = np.array([1, 2, 3])
output = forward(x)
print(output)
```
在这个例子中,我们首先定义了神经网络的结构,包括输入层、隐藏层和输出层的神经元数量。然后,我们使用 `numpy` 库初始化了权重,并定义了一个 sigmoid 激活函数。最后,我们定义了一个前向传输函数,该函数接受一个输入向量并计算网络的输出。我们使用 `numpy` 的 `dot` 函数来计算加权输入和输出,并使用 sigmoid 激活函数来将结果映射到介于 0 和 1 之间的值。最后,我们使用前向传输函数测试了我们的神经网络。
阅读全文
相关推荐

















