TensorFlow安装、变量学习和常用操作

版权声明:用心写好你的每一篇文章,我的个人博客已上线:http://thinkgamer.cn https://blog.csdn.net/Gamer_gyt/article/details/79968940



打开微信扫一扫,关注微信公众号【数据与算法联盟】

转载请注明出处: http://blog.csdn.net/gamer_gyt
博主微博: http://weibo.com/234654758
Github: https://github.com/thinkgamer

安装、入门

环境说明:

  • deepin 15.4
  • python 3.5.4
  • tensorflow 1.7.0

安装:

pip3 install https://pypi.python.org/packages/dd/ed/9e6c6c16ff50be054277438669542555a166ed9f95a0dcaacff24fd3153a/tensorflow-1.7.0rc1-cp35-cp35m-manylinux1_x86_64.whl#md5=ec44ad9b0d040caef8ca0fac5b822b0d

测试:

>>> import tensorflow as tf
>>> hello = tf.constant("hello , Thinkgamer")
>>> with tf.Session() as sess:
...     print(sess.run(hello))
...     sess.close()
... 
2018-03-28 00:50:16.728894: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
b'hello , Thinkgamer'

使用 TensorFlow, 你必须明白 TensorFlow:

  • 使用图 (graph) 来表示计算任务.
  • 在被称之为 会话 (Session) 的上下文 (context) 中执行图.
  • 使用 tensor 表示数据.
  • 通过 变量 (Variable) 维护状态.
  • 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.

session和InteractiveSession的区别:

session:启动图的操作,有run()、close()
InteractiveSession:默认会话

>>> sess = tf.InteractiveSession()
>>> a = tf.constant(5.0)
>>> b = tf.constant(6.0)
>>> c = a * b
>>> print(c.eval())
30.0
>>> sess.close()
>>>
>>> sess = tf.Session()
>>> a = tf.constant(5.0)
>>> b = tf.constant(6.0)
>>> c = a * b
>>> sess.run(c)
30.0
>>> sess.close()

Tensorflow之变量

tensor的理解

tensor即张量,tf中所有的数据通过数据流进行传输,可以声明任何一个张量,只有当一个张量进行run的时候,这个张量所涉及的tensor便会触发,这一点和spark的DAG很是相似,在同一条链上的某个节点进行触发操作时,该节点之前的所有节点便会参与计算。

在tensorflow中,张量的维数被描述为“阶”,张量是以list的形式存储的。list有几重中括号,对应的张量就是几阶。如t=[ [1,2,3],[4,5,6],[7,8,9] ],t就是一个二阶张量。

我们可以认为,一阶张量,如[1,2,3],相当于一个向量,二阶张量,如[ [1,2,3],[4,5,6],[7,8,9] ],相当于一个矩阵。

对于t=[ [1,2,3],[4,5,6],[7,8,9] ]来说,它的shape==>[3,3],shape可以理解成:当脱去最外层的一对中括号后,里面有3个小list,然后每个小list里又有3个元素,所以该张量的shape==>[3,3]。

举几个例子,如[ [1,2,3],[4,5,6] ] 的shape=[2,3](因为当脱去最外层的一对中括号后,里面有2个小list,然后每个小list里又有3个元素,所以该张量的shape==>[2,3]。)

又如:

[
    [ 
        [ [ 2 ], [ 2 ] ] ,
        [ [ 2 ], [ 2 ] ] , 
        [ [ 2 ], [ 2 ] ] 
    ] , 
    [ 
        [ [ 2 ], [ 2 ] ] , 
        [ [ 2 ], [ 2 ] ] , 
        [ [ 2 ], [ 2 ] ] 
    ] ,
    [ 
        [ [ 2 ], [ 2 ] ] , 
        [ [ 2 ], [ 2 ] ] , 
        [ [ 2 ], [ 2 ] ]
    ] ,
    [ 
        [ [ 2 ], [ 2 ] ] ,
        [ [ 2 ], [ 2 ] ] ,
        [ [ 2 ], [ 2 ] ] 
    ] 
]

的shape==>[4,3,2,1] (因为当脱去最外层的一对中括号后,里面有4个第二大的list,每个第二大的list里又有3个第三大的list,每个第三大的list里有2个第四大的list,每个第四大的list里有1个元素,所以该张量的shape==>[4,3,2,1]。

#coding: utf-8

'''
create by: thinkgamer
create time: 2018/04/16
description: 关于tensorflow变量的学习
'''

import tensorflow as tf

a = tf.Variable([ [1,2,3],[4,5,6],[7,8,9] ])
b = tf.Variable([ [1,2,3],[4,5,6] ])
c = tf.Variable([[ [ [ 2 ], [ 2 ] ] ,[ [ 2 ], [ 2 ] ] , [ [ 2 ], [ 2 ] ] ] ,
                 [ [ [ 2 ], [ 2 ] ] ,[ [ 2 ], [ 2 ] ] , [ [ 2 ], [ 2 ] ] ] ,
                 [ [ [ 2 ], [ 2 ] ] ,[ [ 2 ], [ 2 ] ] , [ [ 2 ], [ 2 ] ] ] ,
                 [ [ [ 2 ], [ 2 ] ] ,[ [ 2 ], [ 2 ] ] , [ [ 2 ], [ 2 ] ] ] ])
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
print("a shape: ",a.eval)
print("b shape: ",b.eval)
print("c shape: ",c.eval)

打印出的结果如下:

a shape:  <bound method Variable.eval of <tf.Variable 'Variable_19:0' shape=(3, 3) dtype=int32_ref>>
b shape:  <bound method Variable.eval of <tf.Variable 'Variable_20:0' shape=(2, 3) dtype=int32_ref>>
c shape:  <bound method Variable.eval of <tf.Variable 'Variable_21:0' shape=(4, 3, 2, 1) dtype=int32_ref>>

tf实现乘法

# tf 实现矩阵乘法
val1 = tf.Variable([[1,2]])
val2 = tf.Variable([[1],[2]])
result1 = tf.matmul(val1,val2)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(result1))
    sess.close()

tf的常用操作

# tf的常用操作,建议变量以float32为主,CPU,GPU均支持,否则容易出现一些错误,float32需要从tf中引入
from tensorflow import float32

# 创建一个shape=(3,4)的tensor
t1 = tf.zeros([3,4],float32)

# 创建一个shape类似于tensor的tensor,值分为全为0或1
tensor = tf.Variable([ [1,2,3],[4,5,6],[7,8,9] ])
t2 = tf.zeros_like(tensor)
t3 = tf.ones_like(tensor)

# 创建tensorflow支持的常量
t4 = tf.constant([1,2,3,4])

# 创建常量,指定值全为-1
t5 = tf.constant(-1.0,shape=[2,3])

# 创建数组
t6 = tf.linspace(1.0,6.0,3,name="linspace")
# start=1, limit=9, delta=3
t7 = tf.range(1,9,3)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print("t1: ",sess.run(t1))
    print("\ntermsor: ",sess.run(tensor))
    print("\nt2: ",sess.run(t2))
    print("\nt3: ",sess.run(t3))
    print("\nt4: ",sess.run(t4))
    print("\nt5: ",sess.run(t5))
    print("\nt6: ",sess.run(t6))
    print("\nt7: ",sess.run(t7))
sess.close()

#-----------------------------------------
# tf创建符合指定正态分布的tensor
t8 = tf.random_normal([2,3],mean=-1 ,stddev=4)

# tf shuffle
t9 = tf.constant([[1,2],[3,4],[5,6]])
t10 = tf.random_shuffle(t9)

sess = tf.Session()
print("\nt8:",sess.run(t8))
print("\nt9:",sess.run(t9))
print("\nt10",sess.run(t10))

打印出的值为:

t1:  [[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

termsor:  [[1 2 3]
 [4 5 6]
 [7 8 9]]

t2:  [[0 0 0]
 [0 0 0]
 [0 0 0]]

t3:  [[1 1 1]
 [1 1 1]
 [1 1 1]]

t4:  [1 2 3 4]

t5:  [[-1. -1. -1.]
 [-1. -1. -1.]]

t6:  [1.  3.5 6. ]

t7:  [1 4 7]

t8:  [[  0.8365586   5.152416   -3.9977255]
 [ -1.7592524 -12.675492   -5.949805 ]]

t9:  [[1 2]
 [3 4]
 [5 6]]

t10:  [[3 4]
 [5 6]
 [1 2]]
In [ ]:

tf实现i++

# tf 实现i++
state= tf.Variable(1)
new_value = tf.add(state,tf.Variable(1))
update = tf.assign(state,new_value)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(state))
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

打印结果为:

1
2
3
4

numpy转tensor

# numpy 转化为 tensor
import numpy as np
np1 = np.zeros((3,3))
ta = tf.convert_to_tensor(np1)
with tf.Session() as tf:
    print(sess.run(ta))

测试遇到的问题

1:tensorFlow与python版本不适应

现象:NameError: name ‘XXX’ is not defined
原因是:当前tensorflow版本与python版本不适应。
解决办法:重新安装tf

pip3 install --upgrade tensorflow

------------
Collecting tensorflow
  Downloading tensorflow-1.6.0-cp35-cp35m-manylinux1_x86_64.whl (45.8MB)

2:变量未初始化

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_58

解决办法:将变量进行初始化

init = tf.global_variables_initializer()
tf.Session().run(init)



打开微信扫一扫,加入数据与算法交流大群

猜你喜欢

转载自blog.csdn.net/Gamer_gyt/article/details/79968940