TensorFlow common operations: Code Example

1, an example of the code matrix is ​​defined:

import tensorflow as tf

tf.zeros([3,4]) #定义3行4列元素均为0的矩阵

tensor=tf.constant([1,2,3,4])#定义一维向量常量

#'tensor' =[[1,2,3],[4,5,6]]
tf.ones_like(tensor) #定义大小和tensor变量大小相同的元素均为1的矩阵


tensor1=tf.constant(1.0,shape=[2,3])#定义2行3列元素均为1.0的常量矩阵

tf.linspace(1.0, 6.0, 1, name="linspac")#起始值为1.0,终止值为6.0,步长为1

tf.range=(1,0, 6.0, 1)#start=1.0,limit=6.0,delta=1(不包括6.0)

norm = tf.random_normal([3,4],mean =1, stddev =4)#3行4列均值为1,标准差为4的随机矩阵

shuff = tf.random_shuffle(tensor),#随机打乱矩阵中元素的位置

with tf.Session() as sess: 
      print(sess.run(norm))
      print(sess.run(shuff))

Operating results:
Here Insert Picture Description
TensorFlow common operations when defining matrices and numpy almost. Can also use the API corresponding matrix defined numpy directly converted format supported TensorFlow

import tensorflow as tf
import numpy as np
a= np.zeros([4,4])
ta= tf.convert_to_tensor(a)
with tf.Session() as sess: 
      print(sess.run(ta))

2, sample code loop iteration (for loop):

import tensorflow as tf

a = tf.Variable(0)
New_a = tf.add(a, tf.constant(1)) 
update =tf.assign(a,New_a) #赋值操作(a=New_a)

with tf.Session() as sess: 
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    print( sess.run(a))
    for _ in range(3):
        sess.run(update) #累加迭代
        print(sess.run(a)) 
       

3, allocates memory (placeholder)

import tensorflow as tf

input1=tf.placeholder(tf.float32)  #建议使用tf.float32类型
input2=tf.placeholder(tf.float32)
output= tf.add(input1, input2)
with tf.Session() as sess: 
      print(sess.run([output],feed_dict={input1:[7.0],input2:[3.0]}))

Guess you like

Origin blog.csdn.net/qq_43660987/article/details/92067179