Tensorflow学习-1

Tensorflow学习-1node

 

     人生若只如初见,何事秋风悲画扇。ide

 

简介:Tensorflow基本使用、常量/变量、tensorflow2.0兼容tensorflow1.0版本。学习

1、代码示例优化

 1 import tensorflow as tf  2 
 3 print("tensorFlow version is: " + tf.__version__)  4 
 5 # 建立两个常量
 6 node1 = tf.constant([[3.0, 1.5], [2.5, 6.0]], tf.float32)  7 node2 = tf.constant([[4.0, 1.0], [5.0, 2.5]], tf.float32)  8 # 定义加法运算
 9 node3 = tf.add(node1, node2) 10 # 输出为一个tensor, shape=(2, 2) 即 两行两列,shape为张量的维度信息
11 print("********** node1 is ***********") 12 print(node1) 13 print("********** node3 is ***********") 14 print(node3) 15 
16 # 输出运算结果Tensor的值
17 print("经过 numpy() 方法输出Tensor的值:") 18 print(node3.numpy()) 19 
20 # scalar == 标量,vector == 向量,张量 == Tensor
21 scalar = tf.constant(100) 22 vector = tf.constant([1, 2, 3, 4, 5]) 23 matrix = tf.constant([[1, 2, 3], [4, 5, 6]]) 24 cube_matrix = tf.constant([[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]]) 25 
26 print("*******scalar == 标量,vector == 向量,张量 == Tensor******") 27 print(scalar.shape) 28 print(vector.shape) 29 print(matrix.shape) 30 print(cube_matrix.get_shape()) 31 print(cube_matrix.numpy()[1, 2, 0])  # 按下标获取指定位置的元素
32 
33 a = tf.constant([1, 2]) 34 b = tf.constant([2.0, 3.0]) 35 
36 a = tf.cast(a, tf.float32) 37 result = tf.add(a, b) 38 print("result a+b is: ", result) 39 
40 # 建立在运行过程当中不会改变的单元,常量constant,在建立常量时,只有value值是必填的,dtype等参数能够缺省
41 # tf.constant(
42 # value,
43 # dtype=None,
44 # shape=None,
45 # name='Tao'
46 # )
47 com1 = tf.constant([1, 2]) 48 com2 = tf.constant([3, 4], tf.float32) 49 com3 = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])  # 若shape参数被设值,则会作相应的reshape操做
50 print("com3 is: ", com3) 51 
52 # 建立在运行过程当中值能够被改变的单元, 变量Variable
53 # tf.Variable(
54 # initial_value,
55 # dtype=None,
56 # shape=Node,
57 # trainable=True, 是否被自动优化
58 # name='Variable'
59 # )
60 v1 = tf.Variable([1, 2]) 61 v2 = tf.Variable([3, 4], tf.float32)  # 变量的dtype是根据初始值肯定的,此处设置了可是dtype仍未int32
62 print("Variable v1 is: ", v1) 63 print("Variable v2 is: ", v2) 64 # 变量赋值语句 assign()
65 v3 = tf.Variable(5) 66 v3.assign(v3 + 1) 67 print("v3 is: ", v3) 68 v3.assign_add(1) 69 v3.assign_sub(2) 70 print("v3 now is: ", v3) 71 
72 # Tensorflow2把Tensorflow1中的全部API整理到2中的tensorflow.compat.v1包下
73 # 在版本2中执行1的代码,可作以下修改:
74 # 一、导入Tensorflow时使用 import tensorflow.compat.v1 as tf 代替 import tensorflow as tf
75 # 二、执行tf.disable_eager_execution() 禁用Tensorflow2默认的即便执行模式
View Code~拍一拍小轮胎

2、运行结果spa

 

 

 

人生若只如初见scala

      何事秋风悲画扇code

相关文章
相关标签/搜索