说明:1.关于tensorflow的代码是参考了b站练数成金的代码,链接地址:https://www.bilibili.com/video/av20542427/?p=1
2.部分代码还参考了tensorflow中文社区的网站,以及tensorflow的官网(需要梯子)。
tensorflow中文社区的网站:http://www.tensorfly.cn/
目录
2-1.创建图和启动图
import tensorflow as tf
#创建一个常量op
m1 = tf.constant([[3,3]])
#创建一个常量op
m2 = tf.constant([[2],[3]])
#创建一个矩阵乘法op,把m1和m2传入
product = tf.matmul(m1,m2)
print(product)#打印不出来结果,需使用下面语句
Tensor("MatMul_1:0", shape=(1, 1), dtype=int32)#这是直接打印出来的结果
启动图:
#定义一个会话,启动默认图
sess = tf.Session()
#调用sess的run方法来执行矩阵乘法的op
#run(product)出发了图中的3个op
result = sess.run(product)
print(result)
sess.close()
[[15]]
我们经常使用下面启动图的方式
with tf.Session() as sess:
result = sess.run(product)
print(result)
[[15]]
2-2.变量的操作
一般加减法操作:
import tensorflow as tf
#创建一个变量
x = tf.Variable([1,2])
a = tf.constant([3,4])
#创建一个减法op
sub = tf.subtract(x,a)
#创建一个加法op
add = tf.add(x,a)
#有变量使用需要初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(sub))
print(sess.run(add))
实时更新变量的值:
#创建一个初始化为0的变量
state = tf.Variable(0,name='counter')
#创建一个state加1的op
new_value = tf.add(state,1)
#赋值op,将new_value的值赋给state
update = tf.assign(state,new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(state))
for _ in range(5):
print(sess.run(update))
2-3 Fecth and Feed
#fetch 运行多个op
input1 = tf.constant(2.0)
input2 = tf.constant(3.0)
input3 = tf.constant(5.0)
add = tf.add(input1,input2)
mul = tf.multiply(input3,add)
with tf.Session() as sess:
result = sess.run([add,mul])
print(result)
#feed
#创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
print(sess.run(output,feed_dict={input1:8.,input2:3.}))#将要执行的数据喂进去
2-4 tensorflow一个线性拟合简单实例
import tensorflow as tf
import numpy as np
#生成100个随机点
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2
#构造一个线性模型
k = tf.Variable(0.)
b = tf.Variable(0.)
y = k * x_data + b
#二次代价函数
loss = tf.reduce_mean(tf.square(y-y_data))
#定义一个梯度下降法优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化代价函数
train = optimizer.minimize(loss)
#初始化变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(201):
sess.run(train)
if step%20 ==0:
print(step,sess.run([k,b]))
训练结果:最后结果与预定的k和b的大小很接近
0 [0.05440712, 0.10039122] 20 [0.10398124, 0.19783342] 40 [0.1023856, 0.19870181] 60 [0.10142946, 0.19922212] 80 [0.10085656, 0.19953388] 100 [0.10051324, 0.19972071] 120 [0.10030753, 0.19983265] 140 [0.10018428, 0.19989972] 160 [0.10011043, 0.19993991] 180 [0.10006616, 0.199964] 200 [0.10003964, 0.19997843]