例子为:根据传入的零件的质量和长度去判断零件是否合格!
首先明确输入和输出,输入的特征我们首先定为2个及零件的质量个长度,输出也是两个即是否合格,构建三层神经网络,隐藏节点设为3个,对神经网络有兴趣的小伙伴可以看下这个网站---->点击跳转
接下来废话不多说,上代码!
import tensorflow as tf
from numpy.random import RandomState
# 训练数据集的大小,每个数据集有2个属性
batch_size = 8
#设置权重,w1为2行3列,w2为3行一列,w1 为 输入节点的隐藏层的权重,w2 为 隐藏层到输出层的权重
w1 = tf.Variable(tf.random_normal([2,3], stddev = 1,seed = 1))
w2 = tf.Variable(tf.random_normal([3,1], stddev = 1,seed = 1))
#设置输入点,是一个位置,不是数据,每个数据都有两个信息
x = tf.placeholder(tf.float32, shape=(None,2), name = 'X-input')
y_ = tf.placeholder(tf.float32, shape=(None,1), name = 'Y-output')
#神经网络前向传播
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
#设置激活函数sigmoid,sigmoid函数的解为0-1的值
y = tf.sigmoid(y)
#设置损失函数
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))
+ (1 - y_) * tf.log(tf.clip_by_value(1 - y, 1e-10, 1.0)))
#设置训练函数,学习率为0.001
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
#随机生成ram
#所有数据集的大小
#随机生成128个2个属性的数组
rdm = RandomState(1)
X = rdm.rand(128,2)
Y = [[int(x1+x2 < 1)] for (x1, x2) in X]
#判断输出的的值
Y = [ [int(xl+x2 < 1)] for (xl , x2 ) in X ]
#print(Y)
#声明一个会话,tf的运行建立在一个会话之上
with tf.Session() as sess:
#初始化图上的变量
init_op = tf.global_variables_initializer()
sess.run(init_op)
#输出初始化的权重
print(sess.run(w1))
print(sess.run(w2))
#迭代次数
step = 5000
#迭代
for i in range(step):
start = (i * batch_size) % datasize
end = min(start+batch_size,datasize)
#训练
sess.run(train_step, feed_dict={x:X[start:end], y_ : Y[start:end]})
#输出日志
if i % 1000 == 0:
total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y})
print("After %d training step(s), cross entropy on all data is %g" % (i, total_cross_entropy))
#训练后的权重
print(sess.run(w1))
print(sess.run(w2))
输出结果为:
[[-0.8113182 1.4845988 0.06532937] [-2.4427042 0.0992484 0.5912243 ]] [[-0.8113182 ] [ 1.4845988 ] [ 0.06532937]] After 0 training step(s), cross entropy on all data is 0.849859 After 1000 training step(s), cross entropy on all data is 0.667049 After 2000 training step(s), cross entropy on all data is 0.660471 After 3000 training step(s), cross entropy on all data is 0.659925 After 4000 training step(s), cross entropy on all data is 0.659278 [[-0.2494851 0.29811788 1.744163 ] [-1.8716735 -0.6003619 1.5063392 ]] [[-0.04966074] [ 0.26192534] [-1.2656436 ]]