搭建:anaconda + tensorflow
begin:
import tensorflow as tf
data1 = tf.constant(2, dtype=tf.int32)
data2 = tf.Variable(10, name='var')
print(data1, data2)
sess = tf.Session()
'''
print(sess.run(data1))
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(data2))
sess.close()
'''
init = tf.global_variables_initializer()
with sess:
sess.run(init)
print(sess.run(data2))
tf.Session() 会话
init = tf.global_variables_initializer()
init = tf.initialize_all_variables()
{WARNING:tensorflow:From C:\Users\cd\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\util\tf_should_use.py:193: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use tf.global_variables_initializer instead.}
输出:
Tensor("Const:0", shape=(), dtype=int32) <tf.Variable 'var:0' shape=() dtype=int32_ref>
10
基础运算:
import tensorflow as tf
data1 = tf.constant(6)
data2 = tf.constant(2)
dataAdd = tf.add(data1, data2)
dataMul = tf.multiply(data1, data2)
dataSub = tf.subtract(data1, data2)
dataDiv = tf.divide(data1, data2)
with tf.Session() as sess:
print(sess.run(dataAdd))
print(sess.run(dataMul))
print(sess.run(dataSub), sess.run(dataDiv))
输出:
8
12
4 3.0
矩阵运算:
import tensorflow as tf
data1 = tf.constant([6,6])
data2 = tf.constant([[2],
[2]])
data3 = tf.constant([[1,2],
[3,4],
[5,6]])
print(data3.shape)
with tf.Session() as sess:
print(sess.run(data3))
print(sess.run(data3[0]))
print(sess.run(data3[:,0]))
输出:
(3, 2)
[[1 2]
[3 4]
[5 6]]
[1 2]
[1 3 5]
其它:
import tensorflow as tf
mat1 = tf.constant([[0,0,0],[0,0,0]])
mat2 = tf.zeros([2,3])
mat3 = tf.fill([2,3],14)
mat4 = tf.zeros_like(mat1)
mat5 = tf.linspace(0.0,2.0,11)
mat6 = tf.random_uniform([2,3],-1,2)
with tf.Session() as sess:
print(sess.run(mat1))
print(sess.run([[mat2],[mat3]]))
print(sess.run(mat4))
print(sess.run(mat5))
print(sess.run(mat6))
输出:
[[0 0 0]
[0 0 0]]
[[array([[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)], [array([[14, 14, 14],
[14, 14, 14]])]]
[[0 0 0]
[0 0 0]]
[ 0. 0.2 0.40000001 0.60000002 0.80000001 1.
1.20000005 1.39999998 1.60000002 1.80000007 2. ]
[[ 0.44188511 1.27390599 1.53598404]
[ 0.39836574 1.29693556 0.00948727]]
本文详细介绍如何使用Anaconda环境搭建TensorFlow开发平台,并演示了基本的数据类型操作、算术运算、矩阵运算,以及创建常用张量的方法。通过实例,读者可以快速掌握TensorFlow的基本用法。
1489

被折叠的 条评论
为什么被折叠?



