TensorFlow学习笔记:5、矩阵的简单运算

版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/chengyuqiang/article/details/88796381
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 15:22:50 2019

@author: hadron
"""

import tensorflow as tf

# 例1:计算两个矩阵的和
# 定义了两个常量op,m1和m2,均为1*2的矩阵 、
m1=tf.constant([3,5]) 
m2=tf.constant([2,4]) 
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.]]

运行结果

Python 3.7.1 | packaged by conda-forge | (default, Mar 13 2019, 13:32:59) [MSC v.1900 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.3.0 -- An enhanced Interactive Python.

runfile('D:/ai/py/tensorflow-matrix.py', wdir='D:/ai/py')
[5 9]
矩阵相乘的结果: [[12.]]

猜你喜欢

转载自blog.csdn.net/chengyuqiang/article/details/88796381