Tensorflow 框架搭建神经网络(四)


# Copyright (c)2018, 东北大学软件学院学生
# All rightsreserved
# 文件名称:test.py
# 作   者:孔云
#问题描述:利用placeholder实现输入定义
#coding:utf-8
#两层简单神经网络(全连接)
import tensorflow as tf
#定义输入和参数
#用placeholder实现输入定义 (sess.run中喂一组数据)
x = tf.placeholder(tf.float32, shape=(1, 2))
w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
#定义前向传播过程
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
#用会话计算结果
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op) #初始化变量
    print("the result of y is:\n",sess.run(y, feed_dict={x: [[0.7,0.5]]}))

运行结果如下:


上述代码利用placeholder实现输入定义,在sess.run中喂一组数据。下面实现在sess.run中喂多组数据,代码如下:

#coding:utf-8
#两层简单神经网络(全连接)
import tensorflow as tf
#定义输入和参数
#用placeholder定义输入(sess.run喂多组数据)
x = tf.placeholder(tf.float32, shape=(None, 2))
w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
#定义前向传播过程
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
#调用会话计算结果
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print ("the result of y is:\n",sess.run(y, feed_dict={x: [[0.7,0.5],[0.2,0.3],[0.3,0.4],[0.4,0.5]]}))
    print ("w1:\n", sess.run(w1))
    print("w2:\n", sess.run(w2))

运行结果如下:


注:由上述两段代码知,我们可以一次喂入一组或多组输入, 让神经网络计算输出 y, 可以先用 tf.placeholder 给输入占位。 如果一次喂一组数据 shape 的第一维位置写 1, 第二维位置看有几个输入特征,就写几个; 如果一次想喂多组数据, shape 的第一维位置可以写 None 表示先空着, 第二维位置写有几个输入特征。

猜你喜欢

转载自blog.csdn.net/u012369559/article/details/79980549