用tensorflow实现正向传播和反向传播的一个小demo

用例:输入采用numpy生成一个10×5的矩阵作为X,用numpy生成一个1×5的矩阵作为系数W

函数:y = W·X(点乘)

代码:

# coding:utf-8

import tensorflow as tf
import numpy as np


a = np.random.random((10, 5))
matrix1 = tf.convert_to_tensor(a)
c = np.random.random((1, 5))
matrix3 = tf.convert_to_tensor(c)
print('输入矩阵:\n', a)
print('点乘系数:\n', c)


def f(x, w):
    product_1 = tf.multiply(x, w)  # 矩阵点乘(内积)
    return product_1


y = f(matrix1, matrix3)
# print(y)
# exit()

dy = tf.gradients(y, matrix1)
with tf.Session() as sess:
    print('点乘函数运行完毕,输出为:\n', sess.run(y))
    print('求导(反向传播)求出点乘系数:\n', sess.run(dy))

使用tensorflow的求导方法,输出结果和预期一致,

即:正向-》知道输入矩阵、系数(或称为函数、算法)可以求出输出矩阵,

       反向-》知道输入矩阵、输出矩阵,可以通过求导方法求出系数(或称为函数、算法)

猜你喜欢

转载自blog.csdn.net/glin_mk/article/details/81020663
今日推荐