Tensorflow2实现三层神经网络的前向传输

使用Tensorflow2自己实现三层神经网络的前向传输

导入所需要的包

import tensorflow as tf

导入数据集,本次采用的tensorflow提供的经典是mnist手写数据集

# x:[60k,28,28],
# y:[60k]
(x, y),_ = tf.keras.datasets.mnist.load_data()
# x:[0-255]->[0,1]    y:[0-9]
# 将x,y 转换为Tensor,并且将x归一化
x = tf.convert_to_tensor(x, dtype=tf.float32)/255.
y = tf.convert_to_tensor(y, dtype=tf.int32)
print(x.shape,y.shape,x.dtype,y.dtype) 

输出x,y的shape为下图,x表示60000张28*28 的图片,y对应60000个标签,范围为【0-9】输出x,y的形状
设置batch为128,即一次训练128条数据。

# 设置batch为128
train_db = tf.data.Dataset.from_tensor_slices((x,y)).batch(128)
train_iter = iter(train_db)
sample = next(train_iter)
# 一个batch的形状
print('batch:',sample[0].shape,sample[1].shape)

以下为训练所需参数和过程,本次设计为三层神经网络。输入层为28*28的图片,节点为784,第二层为256个节点,第三层为128个节点,输出层为10个节点,注释中,b为训练数据的个数(维数)。

# 创建权值
# 降维过程 [b,784]->[b,256]->[b,128]->[b,10]
# [dim_in, dim_out],[dim_out]
# 随机生成一个权重矩阵,并且初始化每一层的偏置
# 由于下文中的梯度下降法,tape默认只会跟踪tf.Variable类型的信息,所以进行转换。
w1 = tf.Variable(tf.random.truncated_normal([784,256],stddev=0.1))
b1 =  tf.Variable(tf.zeros([256]))
w2 =  tf.Variable(tf.random.truncated_normal([256,128],stddev=0.1))
b2 =  tf.Variable(tf.zeros([128]))
w3 =  tf.Variable(tf.random.truncated_normal([128,10],stddev=0.1))
b3 =  tf.Variable(tf.zeros([10]))
lr = 1e-3  #0.001   10的-3次方

训练过程如下代码,设置epoch为10:

for epoch in range(10):
    # enumerate处理后可以返回当前步骤的step,便于打印当前信息
    print('epoch',epoch)
    for step,(x,y) in enumerate(train_db):
        #x :[128,28,28]
        #y :[128]
        x = tf.reshape(x,[-1,28*28])
        with tf.GradientTape() as tape:  
            # x :[128,28*28]
            # h1 = x@w1+b1
            # [b,784]@[784*256]+[256]->[b,256]+[256]->[b,256]+[b,256]
            h1 = x@w1 +tf.broadcast_to(b1,[x.shape[0],256])
            h1 = tf.nn.relu(h1)
            h2 =  h1@w2 + b2
            h2 =  tf.nn.relu(h2)

            out =  h2@w3 + b3
            # compute loss 计算误差
            # out:[b,10]
            y_onehot = tf.one_hot(y,depth=10)

            # mse = mean(sum(y-out)^2)
            loss = tf.square(y_onehot-out)
            # mean: scalar
            loss = tf.reduce_mean(loss)
            # compute gradients
            grads = tape.gradient(loss,[w1,b1,w2,b2,w3,b3])
            # w1 = w1 - lr * w1_grad

            w1.assign_sub(lr * grads[0])  # 保持w1原地更新,保持引用不变,类型不变
            b1.assign_sub(lr * grads[1])
            w2.assign_sub(lr * grads[2])
            b2.assign_sub(lr * grads[3])
            w3.assign_sub(lr * grads[4])
            b3.assign_sub(lr * grads[5])

            if step % 100 == 0:
                print(step,'  loss:',float(loss))

运行结果如下图:
0-5
6-10

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 TensorFlow 实现三层 BP 神经网络的代码示例: ```python import tensorflow as tf # 定义训练数据 x_train = [[0, 0], [0, 1], [1, 0], [1, 1]] y_train = [[0], [1], [1], [0]] # 定义输入和输出节点数 input_dim = 2 output_dim = 1 # 定义中间层节点数 hidden_dim = 2 # 定义输入和输出占位符 x = tf.placeholder(tf.float32, [None, input_dim]) y = tf.placeholder(tf.float32, [None, output_dim]) # 定义权重和偏置 w1 = tf.Variable(tf.random_normal([input_dim, hidden_dim])) b1 = tf.Variable(tf.zeros([hidden_dim])) w2 = tf.Variable(tf.random_normal([hidden_dim, output_dim])) b2 = tf.Variable(tf.zeros([output_dim])) # 定义向传播过程 hidden_layer = tf.sigmoid(tf.matmul(x, w1) + b1) output_layer = tf.sigmoid(tf.matmul(hidden_layer, w2) + b2) # 定义损失函数 cross_entropy = -tf.reduce_sum(y * tf.log(output_layer) + (1 - y) * tf.log(1 - output_layer)) # 定义训练操作 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy) # 初始化变量 init = tf.global_variables_initializer() # 开始训练 with tf.Session() as sess: sess.run(init) for i in range(10000): sess.run(train_step, feed_dict={x: x_train, y: y_train}) if i % 1000 == 0: print('Epoch:', i) print('Output:', sess.run(output_layer, feed_dict={x: x_train})) ``` 上述代码实现了一个包含两个输入节点、两个隐藏节点和一个输出节点的三层神经网络,使用交叉熵作为损失函数,使用梯度下降算法进行训练。在训练过程中,我们将训练数据传入神经网络,并输出神经网络的输出值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值