Tensorflow學習-1
人生若只如初見,何事秋風悲畫扇,
簡介:Tensorflow基本使用、常量/變數、tensorflow2.0兼容tensorflow1.0版本,
一、代碼示例
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 # 1、匯入Tensorflow時使用 import tensorflow.compat.v1 as tf 代替 import tensorflow as tf
75 # 2、執行tf.disable_eager_execution() 禁用Tensorflow2默認的即使執行模式
View Code~拍一拍小輪胎
二、運行結果

人生若只如初見
何事秋風悲畫扇
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/240400.html
標籤:其他

