使用TensorFlow進行矩陣的運算

 以下是完整代碼:

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 15:22:50 2019

@author: hadron
"""
#矩陣的運算20190713


import tensorflow as tf

# 例1:計算兩個矩陣的和
# 定義了兩個常量op,m1和m2,均爲1*2的矩陣 、
m1=tf.constant([[3,5],[5,6]])
m2=tf.constant([[2,4],[2,6]])
result=tf.add(m1,m2)
# 注意這裏不需要執行ss.close(),with tf.Session() as ss這句後面會自動關閉
with tf.Session() as sess:
    print(sess.run(result))


# 例2 :矩陣相乘(Matrix Multiplication)
# 創建一個 Constant op ,產生 1x2 矩陣.
matrix1 = tf.constant([[3., 3.]])
# 創建另一個 Constant op 產生  2x1 矩陣.
matrix2 = tf.constant([[2.], [2.]])
# 創建一個 Matmul op 以 'matrix1' 和 'matrix2' 作爲輸入.
# 返回的值, 'product', 表達了矩陣相乘的結果
product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
    result = sess.run(product)
    print('矩陣相乘的結果:', result)
    # ==> [[ 12.]]


#通過shape定義矩陣的形狀/2行3列
m3 = tf.constant([1,2],shape=[2,3]);

with tf.Session() as sess:
    print(sess.run(m3))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章