- 注意:本笔记的题目,例程均参考自人民邮电出版社的《深度学习基于python语言和TensorFlow平台》,仅供个人记录学习进展使用,侵删。
- 运行结果太大,超出博文限制,故隐藏了结果显示。
初识TensorFlow
例一
- 总分 = 德育分0.6 + 智育分0.3 + 体育分*0.1
- 已知两位学生的3项成绩及总分,但是不知道计算规则,使用神经网络的方法大致推算3项权重是多少。
- 将循环次数定为5000,训练10000次后,误差仅为0.023246765~0.033248901,已经很接近了。
import tensorflow as tf
time = 5000
x1 = tf.placeholder(dtype = tf.float32)
x2 = tf.placeholder(dtype = tf.float32)
x3 = tf.placeholder(dtype = tf.float32)
yTrain = tf.placeholder(dtype = tf.float32)
w1 = tf.Variable(0.1, dtype = tf.float32)
w2 = tf.Variable(0.1, dtype = tf.float32)
w3 = tf.Variable(0.1, dtype = tf.float32)
n1 = x1 * w1
n2 = x2 * w2
n3 = x3 * w3
y = n1 + n2 + n3
loss = tf.abs(y - yTrain)
optimizer = tf.train.RMSPropOptimizer(0.001)
train = optimizer.minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(time):
result = sess.run([train, x1, x2, x3, w1, w2, w3, y, yTrain, loss], feed_dict={x1 : 90, x2 : 80, x3 : 70, yTrain : 85})
print(result)
result = sess.run([train, x1, x2, x3, w1, w2, w3, y, yTrain, loss], feed_dict={x1 : 98, x2 : 95, x3 : 87, yTrain : 96})
print(result)
练习一
- 另一所学校有两名学生3项成绩和总分如下,试解出总分计算规则。
import tensorflow as tf
time = 5000
x1 = tf.placeholder(dtype = tf.float32)
x2 = tf.placeholder(dtype = tf.float32)
x3 = tf.placeholder(dtype = tf.float32)
yTrain = tf.placeholder(dtype = tf.float32)
w1 = tf.Variable(0.1, dtype = tf.float32)
w2 = tf.Variable(0.1, dtype = tf.float32)
w3 = tf.Variable(0.1, dtype = tf.float32)
n1 = x1 * w1
n2 = x2 * w2
n3 = x3 * w3
y = n1 + n2 + n3
loss = tf.abs(y - yTrain)
optimizer = tf.train.RMSPropOptimizer(0.001)
train = optimizer.minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(time):
result = sess.run([train, x1, x2, x3, w1, w2, w3, y, yTrain, loss], feed_dict={x1 : 92, x2 : 98, x3 : 90, yTrain : 94})
print(result)
result = sess.run([train, x1, x2, x3, w1, w2, w3, y, yTrain, loss], feed_dict={x1 : 92, x2 : 99, x3 : 98, yTrain : 96})
print(result)
- 通过观察最后两项结果,权重约为
- w1: 0.38913646~0.39013645
- w2: 0.37099329~0.37199807
- w3: 0.23656371~0.23760301
- 猜测权重为W1:0.4, W2:0.4, W3:0.2