TensorFlow 添加一个神经网络层

本文通过两个具体实例,详细介绍了如何使用TensorFlow构建神经网络层。首先,展示了一个通用的神经网络层添加方法,包括权重、偏置的初始化,以及激活函数的应用。随后,构建了一个包含输入层、隐藏层和输出层的神经网络模型,具体参数为:输入层784个节点,隐藏层500个节点,输出层10个节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子一、添加一个神经网络层

详见:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/3-1-add-layer/

import tensorflow as tf

def add_layer(inputs, input_size, output_size, activation_function = None):
    Weights = tf.Variable(tf.random_normal([input_size, output_size]))
    biases = tf.Variable(tf.zeros([1, output_size]) + 0.1) #biases初始化为0.1的列向量
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

 

例子二:定义神经网络,神经网络包含输入层,隐藏层,输出层,输入层有784个节点,输出层有10个节点,隐藏层有500个节点

# 输入层
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

# ///////////////////隐藏层//////////////////////
w1 = tf.Variable(tf.truncated_normal([784, 500], stddev=0.1))
b1 = tf.Variable(tf.zeros([500]))
L1 = tf.nn.relu(tf.matmul(x, w1) + b1)

w2 = tf.Variable(tf.truncated_normal([500, 300], stddev=0.1))
b2 = tf.Variable(tf.zeros([300]))
L2 = tf.nn.relu(tf.matmul(L1, w2) + b2)
# ///////////////////隐藏层//////////////////////

# 输出层
w3 = tf.Variable(tf.truncated_normal([300, 10], stddev=0.1))
b3 = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(L2, w3)+b3)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值