Tensorflow基本用法

tensorflow = tensor张量 + flow流动

模型跑起来需要两步:
(1)描绘整幅图Graph
(2)在Session中执行图里的运算

0-d tensor 标量
1-d tensor 向量
2-d tensor 矩阵

API参考

tensorflow版本查看,指定画图gpu(编号从0开始)

import numpy as np
import tensorflow as tf
#查看tensorflow版本
print(tf.__version__)
print('GPU', tf.test.is_gpu_available())
# 1.13.1
# GPU True

with tf.device('/gpu:0'):
    a=tf.constant([1.0,2.0],name='a')
    b=tf.constant([2.0,3.0],name='b')
    c=tf.add(a,b)

sess=tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))
# [3. 5.]

numpy和tensorflow对比

matrix_1 = np.zeros((3,4))
matrix_1
# array([[0., 0., 0., 0.],
#        [0., 0., 0., 0.],
#        [0., 0., 0., 0.]])

np.reshape(matrix_1, (6,2))
# array([[0., 0.],
#        [0., 0.],
#        [0., 0.],
#        [0., 0.],
#        [0., 0.],
#        [0., 0.]])
matrix_2 = tf.zeros((3,4))
matrix_2
# <tf.Tensor 'zeros:0' shape=(3, 4) dtype=float32>

tf.reshape(matrix_2, (2,6))
# <tf.Tensor 'Reshape:0' shape=(2, 6) dtype=float32>

print(matrix_2)
# Tensor("zeros:0", shape=(3, 4), dtype=float32)

tf.Session,graph&session

a=tf.add(3,5)   #画图
sess=tf.Session()   #Session会在计算图里找到a的依赖,把依赖得节点都进行计算
print(sess.run(a))
sess.close()
# 8

a=tf.add(3,5)
with tf.Session() as sess:
    print(sess.run(a))
# 8
x=2
y=3
op1 = tf.add(x,y)
op2 = tf.multiply(x,y)
op3 = tf.pow(op2,op1)

with tf.Session() as sess:
    op3 = sess.run(op3)
    print(op3) 
# 7776

tf.constant & tf.Variable

tf.constant是op
tf.Variable是一个类,初始化的对象有多个op【对象上的方法操作】
x=tf.Variable(…)
x.initializer 初始化变量
x.value() 读取变量
x.assign(…) 变量写入操作
x.assign_add(…) 更多

变量在使用前,必须初始化,不初始化就会报错

#变量初始化1:初始化全部变量方法
init=tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
#变量初始化2:初始化一个变量子集a b
a=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([784,10]))
init_ab=tf.variables_initializer([a,b],name='init_ab')
with tf.Session() as sess:
    sess.run(init_ab)
#变量初始化3:初始化单个变量
W=tf.Variable(tf.zeros([784,10]))
with tf.Session() as sess:
    sess.run(W.initializer)

输出变量内容——>eval()函数:

W=tf.Variable(tf.truncated_normal([700,100]) ,name="sample")   #初始化一个700*100的随机变量
with tf.Session() as sess:
    sess.run(W.initializer)
    print(W)
    print(W.eval())
# <tf.Variable 'sample_1:0' shape=(700, 100) dtype=float32_ref>
# [[-1.2486352  -1.4302675  -0.2854604  ...  1.557378   -1.401194
#   -0.5477726 ]
#  [ 0.7663887  -0.8839551  -0.9187438  ...  1.1452507   0.4985558
#   -0.735523  ]
#  [-0.36915746  0.569842   -0.77046365 ...  1.0051925  -0.38976425
#    1.421997  ]
#  ...
#  [-1.781231   -0.6531526   0.19805528 ... -1.5581213   0.8666133
#   -1.2377511 ]
#  [-0.41678655 -0.75198644 -0.8673228  ...  0.873077    0.11097283
#    1.1230524 ]
#  [ 1.4358085  -0.4306798   0.21323158 ...  0.315431   -0.9508001
#    1.2597985 ]] 

tensorboard

linux=>
python [yourprogram].py
tensorboard --logdir=="./graphs" --port 7001

windows===>
cmd=> tensorboard --logdir=“C:\Users\86151\TensorFlow\graphs”

浏览器输入=> localhost:6006

a=tf.constant([[2,5]],name='a')
b=tf.constant([[0,1],[2,3]],name='b')
x=tf.multiply(a,b,name='dot_product')   #点乘 - 逐点元素乘法 每个元素*每一列
y=tf.matmul(a,b,name='mat_mul')   #矩阵乘法
with tf.Session() as sess:
	# 定义完计算图,运行session之前使用summary writer把图信息以日志形式dump到本地
    writer=tf.summary.FileWriter('./graphs/const_mul_2', sess.graph)
    print(sess.run(x))
    print(sess.run(y))
writer.close()
# [[ 0  5]
#  [ 4 15]]
# [[10 17]]

一个Session同时跑几个op:tf.Session.run

t f . S e s s i o n . r u n ( f e t c h e s , f e e d _ d i c t = N o n e , o p t i o n s = N o n e , r u n _ m e t a d a t a = N o n e ) tf.Session.run(fetches, feed\_dict=None, options=None, run\_metadata=None) tf.Session.run(fetches,feed_dict=None,options=None,run_metadata=None)

x=3
y=2
add_op=tf.add(x,y)
mul_op=tf.multiply(x,y)
useless=tf.multiply(x,add_op)
pow_op=tf.multiply(add_op,mul_op)
with tf.Session() as sess:
	# 一个Session同时跑几个op,传给sess.run一个list
    z, not_useless = sess.run([pow_op, useless])
    print(z, not_useless)
# 30 15

placeholder数据容器-存放训练的数据

t f . p l a c e h o l d e r ( d t y p e , s h a p e = N o n e , n a m e = N o n e ) tf.placeholder(dtype,shape=None,name=None) tf.placeholder(dtype,shape=None,name=None)

a=tf.placeholder(tf.float32, shape=[3])   #初始化一个1*3的向量,没给值,只是开辟空间
b=tf.constant([5,5,5], tf.float32)   #初始化一个1*3取值全是5的向量
c=a+b   #tf.add(a,b)的简写
with tf.Session() as sess:
    print(sess.run(c, {a:[1,2,3]}))   #通过字典,把a灌进去
# [6. 7. 8.]    

a=tf.add(2,5)
b=tf.multiply(a,3)
with tf.Session() as sess:
    replace_dict={a: 15}
    print(sess.run(b, feed_dict=replace_dict))   #a有初始值,通过feed_dict可以重新给a赋值
# 45
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值