Tensorflow 写构建神经网络

转自:https://blog.csdn.net/roseki/article/details/70171684

import tensorflow as tf
import numpy as np
learning_rate = 0.01 #学习速率
batch_size = 16      #输入数据个数
epoch_step = 10000   # 遍历总数
display_step = 100   #中间结果
x = tf.placeholder("float",[None,20])   #输入层
y = tf.placeholder("float",[None,5])    #输出层
layer1 = 16      #第一层隐藏神经元个数
layer2 = 32      #第二层隐藏神经元个数
#神经网络参数 w,b
alldate = 16
w = {
    "h1":tf.Variable(tf.random_normal([20,layer1])),
    "h2":tf.Variable(tf.random_normal([layer1,layer2])),
    "out":tf.Variable(tf.random_normal([layer2,5]))
}

#h1 表示输入层到隐藏层的权重,输入层有20个神经元,隐藏层神经元个数为layer1,所以维度为[20,layer1]
#h2 同理
#out 表示第二层隐藏层到输出层的权重
#tf.Variable 用来定义变量的函数,tf.random_normal是随机生成的正太分布函数

b = {
    "h1":tf.Variable(tf.random_normal([layer1])),
    "h2":tf.Variable(tf.random_normal([layer2])),
    "out":tf.Variable(tf.random_normal([5]))
}

# 定义神经网络函数
# tf.nn.relu是非线性激励函数,常用的还有tf.sigmoid,tf.tanh
# tf.matmul 是矩阵相乘
# output 是输出

def network(x_input,weight,biases):
    net1 = tf.nn.relu(tf.matmul(x_input,weight["h1"]) + biases["h1"])
    net2 = tf.nn.relu(tf.matmul(net1,weight["h2"]) + biases["h2"])
    output = tf.matmul(net2,weight["out"]) + biases["out"]
    return output

#分类问题中,神经网络的输入层输出数据需要经过一层额外的处理,叫做softmax层,softmax层的作用是将输出层的
#数据全部压缩至0~1之间,并且所有和等于1,这就可以理解成将输出层的数据变成概率分布的形式。然后就可以用交叉熵函数定义损失函数了
#TensorFlow中的tf.nn.softmax_cross_entropy_with_logits损失函数集成上面所说的步骤,即先经过softmax层然后使用交叉熵计算损失
#由此,定义损失函数如下:

pred = network(x,w,b)
cost  = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = pred,labels = y))
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)

#其中pred为预测的数据,即神经网络的输出
#cost即损失函数,tf.reduce_mean 是求平均损失,因为一次性输出入的是多个(batch_size个)数据
#tr.train.AdamOptimizer是选择的优化器,其作用是最小化cost

correct_pred = tf.equal(tf.argmax(y,1),tf.argmax(pred,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,"float"))
#其中correct_pred代表预测正确的标签
#tf.argmax函数返回的是张量在某一维最大值的索引值,由于标签向量是由0,1组成,因此最大值1所在的索引位置就是类别标签。如果pred的最大值所在的索引值等于类别标签的索引值,表示这个结果分类正确
#tf.equal是TensorFlow中判断两个张量是否相等,返回的是一个布尔型张量,如[True,False,False]。
#因为corret_pred是一个布尔型张量,因此需要用tf.cast()函数转化成float型来计算准确率,如[True,False,False,False]会变成[1,0,0,0],经过reduce_mean取平均值0.25来表示准确率。

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(epoch_step):
        avg_cost = 0
        total_batch = int(alldate / batch_size)
        for i in range(total_batch):
            x_batch = np.float32(np.random.rand(batch_size,20))
            y_batch = np.float32(np.random.rand(batch_size,5))
            output = sess.run([optimizer,cost],feed_dict = {x :x_batch,y:y_batch})
            avg_cost += output[1] / total_batch
        if epoch % display_step == 0:
            print("cost:",avg_cost)

    print("finish!")
    test_x = np.float32(np.random.rand(batch_size,20))
    test_y = np.float32(np.random.rand(batch_size,5))
    print("accuracy:",sess.run(accuracy,feed_dict = {x:test_x,y:test_y}))
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值