用TensorFlow搭建全连接神经网络,了解全连接内部运行机制,结果与笔记一致
代码如下(示例):
"""
export CUDA_VISIBLE_DEVICES='7'
cd "$(find ~/ -type f -name "hewu_linear_regression_model_train.py" -exec dirname {} \; -quit)"
/ssddata/home/hewu/anaconda3/envs/tf==1.14/bin/python hewu_linear_regression_model_train.py
"""
import tensorflow as tf
# 高级API,旨在简化深度学习模型的创建,tensorflow 2.0之后版本没有 tensorflow.contrib,如果要使用,可以降低版本为1.14
import tensorflow.contrib.slim as slim
import numpy as np
import sys
import os
def tf_create_bp_model(fingerprint_input):
#(1)定义隐藏层
# 输入层两个特征,隐藏层3个神经元,权重的形状设置为 (2, 3)。
# 每个神经元都有一个对应的偏置值,而且偏置值还可能不一样,这里是为了方便推导,所以写的一样
hidden_weights = np.array([[0.1, 0.2, 0.3],
[0.15, 0.25, 0.35]], dtype=np.float32)
hidden_biases = np.array([0.35,0.35,0.35], dtype=np.float32)
hidden_layer = slim.fully_connected(fingerprint_input, num_outputs=3,
activation_fn=tf.nn.sigmoid, scope='hidden_layer',
weights_initializer=tf.constant_initializer(hidden_weights),
biases_initializer=tf.constant_initializer(hidden_biases))
#(2)定义输出层
out_weights = np.array([[0.4, 0.45],
[0.5, 0.55 ],
[0.6, 0.65 ]], dtype=np.float32)
out_biases = np.array([0.65,0.65], dtype=np.float32)
logits = slim.fully_connected(hidden_layer, num_outputs=2,
activation_fn=tf.nn.sigmoid, scope='out_layer',
weights_initializer=tf.constant_initializer(out_weights),
biases_initializer=tf.constant_initializer(out_biases))
return logits
with tf.name_scope("prepare_stage"):
os.environ['TF_CPP_MIN_LOG_LEVEL']='3' # Successfully opened dynamic library libcudart.so.10.0
print("#######################################################################")
print("TensorFlow version:", tf.__version__)
print("TensorFlow install path:", tf.__path__)
print("gpu_available:", tf.test.is_gpu_available())
print("#######################################################################")
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # WARNING:tensorflow:From bp_model.py:29:
sess = tf.compat.v1.InteractiveSession() # Start a new TensorFlow session.
with tf.name_scope("prepare_data"):
# shape=(None, 2) 表示这个占位符接受一个二维张量,其中第一个维度可以是任意数量的样本,而第二个维度固定为 2,表示每个样本有两个特征。
fingerprint_input = tf.placeholder(tf.float32, shape=(None, 2), name='fingerprint_input')
with tf.variable_scope("define_model"):
# 创建神经网络模型
logits = tf_create_bp_model(fingerprint_input)
# 训练之前,要参数初始化
with tf.name_scope("variables_initial"):
sess.run(tf.global_variables_initializer())
train_fingerprints = np.array([[5, 10]], dtype=np.float32)
# 形状为 (1, 2) 的 numpy 数组,表示有 1 个样本,每个样本有 2 个特征
# np.array([5, 10]) 这是一个形状为 (2,) 的一维数组。它包含两个元素
# np.array([[1], [2]]) (2, 1) 的数组
output_result = sess.run(fetches=logits, feed_dict={fingerprint_input: train_fingerprints})
print("Output from the network:")
print(output_result)
总结
注意:每层的每一个神经元都对应一个偏置值