构造一个有3输入,1个输出的神经网络,其类名为 NeuralNetwork
时间: 2024-11-20 19:43:18 浏览: 17
构建一个名为 `NeuralNetwork` 的神经网络模型通常涉及定义层结构、权重初始化、前向传播等关键组件。这里是一个简单的 Python 示例,使用 TensorFlow 库来创建一个包含一个输入层、两个隐藏层和一个输出层的神经网络:
```python
import tensorflow as tf
class NeuralNetwork:
def __init__(self, input_size, hidden_layer_1_size, hidden_layer_2_size, output_size):
self.input_size = input_size
self.hidden_layer_1_size = hidden_layer_1_size
self.hidden_layer_2_size = hidden_layer_2_size
self.output_size = output_size
# 定义权重和偏置
self.weights = {
'input_hidden1': tf.Variable(tf.random.truncated_normal([self.input_size, self.hidden_layer_1_size])),
'hidden1_hidden2': tf.Variable(tf.random.truncated_normal([self.hidden_layer_1_size, self.hidden_layer_2_size])),
'hidden2_output': tf.Variable(tf.random.truncated_normal([self.hidden_layer_2_size, self.output_size]))
}
self.biases = {
'b_input_hidden1': tf.Variable(tf.zeros([self.hidden_layer_1_size])),
'b_hidden1_hidden2': tf.Variable(tf.zeros([self.hidden_layer_2_size])),
'b_hidden2_output': tf.Variable(tf.zeros([self.output_size]))
}
def forward_pass(self, inputs):
layer_1 = tf.add(tf.matmul(inputs, self.weights['input_hidden1']), self.biases['b_input_hidden1'])
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, self.weights['hidden1_hidden2']), self.biases['b_hidden1_hidden2'])
layer_2 = tf.nn.relu(layer_2)
final_layer = tf.add(tf.matmul(layer_2, self.weights['hidden2_output']), self.biases['b_hidden2_output'])
return final_layer
# 使用示例
input_shape = (None, input_size) # None表示批量大小可以变化
nn = NeuralNetwork(input_shape[1], hidden_layer_1_size, hidden_layer_2_size, output_size)
inputs = tf.placeholder(tf.float32, shape=input_shape)
output = nn.forward_pass(inputs)
```
阅读全文