Skip to content

Commit 1a0b8f1

Browse files
committed
Tensorflow element
1 parent 9a591f2 commit 1a0b8f1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

practice18.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Tensorflow基本運作練習
2+
import tensorflow as tf
3+
4+
# 距陣範例
5+
matrix1 = tf.constant([[2, 2]]) # 1x2
6+
martix2 = tf.constant([[1, 2, 3], [4, 5, 6]]) # 2x3
7+
product = tf.matmul(matrix1, martix2) # 矩陣乘法 shape=(1,3)
8+
9+
# 變數範例
10+
state = tf.Variable(0, name="counter")
11+
12+
one = tf.constant(1)
13+
new_value = tf.add(state, one)
14+
update = tf.assign(state, new_value) # 每次+1之後更新state
15+
16+
init_op = tf.global_variables_initializer() # 初始化
17+
18+
# 資料輸入
19+
input1 = tf.placeholder(tf.float32)
20+
input2 = tf.placeholder(tf.float32)
21+
output = tf.multiply(input1, input2)
22+
23+
# 資料輸出
24+
num1 = tf.constant([3])
25+
num2 = tf.constant([5])
26+
added = tf.add(num1, num2)
27+
multiplied = tf.multiply(num1, num2)
28+
29+
# 執行運算
30+
with tf.Session() as sess:
31+
# 印出矩陣範例
32+
result = sess.run(product)
33+
print(result)
34+
35+
# 印出變數範例
36+
sess.run(init_op)
37+
print(sess.run(state))
38+
for _ in range(3):
39+
sess.run(update)
40+
print(sess.run(state))
41+
42+
# 執行時才將資料以dict輸入
43+
print(sess.run([output], feed_dict={input1: [7], input2: [5]}))
44+
45+
# 直接輸出運算結果
46+
operation = sess.run([added, multiplied])
47+
print(operation)
48+
49+
sess.close()

0 commit comments

Comments
 (0)