TensorFlow 机器学实战指南示例代码之 TensorFlow 的嵌入 Layer

"""
TensorFlow 的嵌入 Layer,用两个矩阵乘以占位符,然后做加法
传入两个形状为 3*5的 numpy 数组,每个矩阵乘以常量矩阵(形状为:5 * 1)
返回一个形状为 3 * 1 的矩阵,紧接着再乘以 1 * 1 的矩阵,返回结果仍为 3*1
再加上一个 3 * 1 的数组
"""

import os
import numpy as np
import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

s = tf.Session()

# 创建数据和占位符
my_array = np.array([[1., 3., 5., 7., 9.],
                     [-2., 0., 2., 4., 6.],
                     [-6., -3., 0., 3., 6.]])
x_vals = np.array([my_array, my_array + 1])
x_data = tf.placeholder(tf.float32, shape=(3, 5))

# 创建矩阵乘法和加法中要用到的常量矩阵
m1 = tf.constant([[1.], [0.], [-1.], [2.], [4.]])
m2 = tf.constant([[2.]])
a1 = tf.constant([[10.]])

# 声明操作,表示成计算图
prod1 = tf.matmul(x_data, m1)
prod2 = tf.matmul(prod1, m2)
add1 = tf.add(prod2, a1)

# 计算图赋值
for x_val in x_vals:
    print(s.run(add1, feed_dict={x_data: x_val}))


猜你喜欢

转载自blog.csdn.net/lingtianyulong/article/details/79265261