基于tensorflow搭建模块化神经网络示例
时间: 2023-07-08 10:54:34 浏览: 134
好的,以下是一个基于TensorFlow搭建模块化神经网络的示例代码:
```python
import tensorflow as tf
# 定义输入层
def create_input_layer(input_size):
return tf.placeholder(tf.float32, shape=[None, input_size], name='input')
# 定义隐层
def create_hidden_layer(input_layer, num_neurons, activation):
input_size = int(input_layer.shape[1])
stddev = 2.0 / tf.sqrt(input_size + num_neurons)
weights = tf.Variable(tf.truncated_normal([input_size, num_neurons], stddev=stddev))
biases = tf.Variable(tf.zeros([num_neurons]))
layer = tf.matmul(input_layer, weights) + biases
if activation:
layer = activation(layer)
return layer
# 定义输出层
def create_output_layer(input_layer, num_classes):
input_size = int(input_layer.shape[1])
stddev = 2.0 / tf.sqrt(input_size + num_classes)
weights = tf.Variable(tf.truncated_normal([input_size, num_classes], stddev=stddev))
biases = tf.Variable(tf.zeros([num_classes]))
layer = tf.matmul(input_layer, weights) + biases
return layer
# 定义模型
def build_model(input_size, hidden_layers, num_classes):
input_layer = create_input_layer(input_size)
hidden_layer = input_layer
for num_neurons, activation in hidden_layers:
hidden_layer = create_hidden_layer(hidden_layer, num_neurons, activation)
output_layer = create_output_layer(hidden_layer, num_classes)
return input_layer, output_layer
# 测试
input_size = 784
hidden_layers = [(256, tf.nn.relu), (128, tf.nn.relu)]
num_classes = 10
input_layer, output_layer = build_model(input_size, hidden_layers, num_classes)
print(input_layer)
print(output_layer)
```
这个示例代码定义了一个三层神经网络,包括一个输入层、两个隐层和一个输出层。其中,输入层和输出层都比较简单,而隐层则是根据输入层的大小、神经元个数和激活函数来创建的。同时,这个代码还支持模型的构建和测试。
阅读全文