使用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))

猜你喜欢

转载自blog.csdn.net/baidu_33512336/article/details/95770655