一:Tensorflow基本概念
1:使用图(graphs)来表示计算任务
2:使用tensor(n维的数组或列表)表示数据
3:在被称之为会话(Session)的上下文(context)中执行图
4:通过变量(Variable )维护状态
5:使用feed和fetch可以为任意的操作赋值或者从其中获取数据
tensorflow是一个编程系统,使用图(graphs)来表示计算任务,图中的节点称之为op(opreation),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。Tensor看作是一个n维的数组或列表。图必须在会话(Session)里被启动。
二:Tensorflow结构
三:基本语法
3-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: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:
#调用sess的run方法来执行矩阵乘法op
#run(product)出发了图中3个op
result = sess.run(product)
print(result)
输出:[[15]]
这里有两种Session的定义方法,后一种会自动关闭Session
3-2:变量
x = tf.Variable([1,2])
a = tf.constant([3,3])
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,sub)
#用于变量初始化
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(sub))
print(sess.run(add))
输出:[-2 -1]
[-1 1]
#创建一个变量初始化0
state = tf.Variable(0,name="counter")
#创建一个op,作用是使state加1
new_value = tf.add(state,1)
#赋值操作,
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))
输出:0
1
2
3
4
5
3-3:fetch和feed
#Fetch
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
add = tf.add(input2,input3)
mul = tf.multiply(input1,add)
with tf.Session() as sess:
result = sess.run([mul,add])
print(result)
输出:[21.0, 7.0]
#Feed
#创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
#feed的数据以字典的形式传入
print(sess.run(output,feed_dict={input1:[7.],input2:[2.]}))
输出:[ 14.]
3-4:tensorflow实例
import tensorflow as tf
import numpy as np
#使用numpy生成100个随机点
x_date = np.random.rand(100)
y_data = x_date*0.1+0.2
#构造一个线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k*x_date + b
#二次代价函数,
#tf.reduce_mean是求平均值
loss = tf.reduce_mean(tf.square(y_data-y))
#定义一个梯度下降法来进行训练的优化器
#tf.train.GradientDescentOptimizer()是梯度下降,0.2是学习率
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]))
输出:0 [0.05431499, 0.10035517]
20 [0.10390387, 0.19787845]
40 [0.10233213, 0.19873264]
60 [0.10139318, 0.1992429]
80 [0.10083226, 0.19954772]
100 [0.10049719, 0.1997298]
120 [0.10029703, 0.19983859]
140 [0.10017744, 0.19990358]
160 [0.10010601, 0.1999424]
180 [0.10006332, 0.19996558]
200 [0.10003783, 0.19997944]