在tensorflow中计算矩阵相乘、点乘(内积)、卷积的方法demo

首先,tensorflow并不神秘,基本相当于numpy和各种model的一个集合,另外比numpy多了两个功能:求张量和求导。numpy的数据组织模式很容易就能转换成tensorflow的数据组织模式,可以作为tensorflow的输入。

在tensorflow中计算矩阵相乘、点乘(内积)、卷积的方法demo。输入数据均使用numpy生成随机多维数组。

并比较numpy点乘和tensorflow点乘的区别,了解输入输出矩阵的shape。

# coding:utf-8

import tensorflow as tf
import numpy as np
import pandas as pd
import time

# 用numpy创建一个 10x5 矩阵
# 加到默认图中.

a = np.random.random((10, 5))
print(a)
# b = []
# b.append(list(a))
matrix1 = tf.convert_to_tensor(a)  # 用于计算相乘和点乘(内积)的矩阵
matrix0 = tf.constant(a, shape=[1, 10, 5, 1])  # 用于计算卷积的矩阵,输入一样,但需要指定特殊的shape
print(matrix0)
print(matrix1)
# exit()
b = np.random.random((5, 3))  # 计算矩阵相乘的矩阵shape
print(b)
c = np.random.random((1, 5))  # 计算内积(矩阵点乘)的矩阵shape
print(c)
matrix2 = tf.convert_to_tensor(b)
print(matrix2)
matrix3 = tf.convert_to_tensor(c)
print(matrix3)
kernel_0 = tf.constant(b, shape=[5, 3, 1, 1])  # 用于计算卷积的矩阵,输入一样,但需要指定特殊的shape

product_0 = tf.matmul(matrix1, matrix2)  # 矩阵相乘
product_1 = tf.multiply(matrix1, matrix3)  # 矩阵点乘(内积)
conv2d = tf.nn.conv2d(matrix0, kernel_0, strides=[1, 1, 1, 1], padding='SAME')  # 卷积
# numpy的点乘(内积)和tensorflow的点乘(内积)稍有区别,numpy是点乘完后按行求和
df = pd.DataFrame(a)
score = np.dot(df, c[0])
print(score, np.shape(score))
# 启动默认图,执行这个乘法操作,并计算耗时
with tf.Session() as sess:
    tic = time.time()
    result_0 = sess.run([product_0])
    result_1 = sess.run([product_1])
    result_2 = sess.run([conv2d])
    print(result_0, np.shape(result_0))
    print(result_1, np.shape(result_1))
    print(result_2, np.shape(result_2))
    toc = time.time()
    print('time cost:'+str(1000*(toc - tic)))

猜你喜欢

转载自blog.csdn.net/glin_mk/article/details/81017263