Tensorflow:关于tensorflow函数

5

我是tensorflow的新手。我有以下问题:

输入:一组浮点数(或者一个动态数组,在Python中列表是要使用的数据类型) 输出:大小为len(input) × len(input)的二维数组

例子1:

输入:

[1.0, 2.0, 3.0]

输出:

[[0.09003057, 0.24472847, 0.66524096], 
 [0.26894142, 0.73105858, 0.0       ], 
 [1.0,        0.0,        0.0       ]]

我曾尝试使用while循环并独立计算每一行并将它们连接起来来创建此功能,但我的教练要求我探索其他方法。
你能给我提供一些解决这个问题的想法吗?

1
你能展示一下带有 while 循环的代码吗? - Distjubo
2
你想对输入做什么? - aarbelle
2个回答

4
你可以通过以下方法实现这一点:
  1. 重复输入数组以创建平铺输入数据的方阵矩阵
  2. 创建一个由左上角为1的掩码
  3. 使用掩码进行softmax。请注意,我们不能在此处使用tf.nn.softmax,因为它也会给那些0赋予小概率。
下面是一个执行此操作的TensorFlow(v0.12.1)代码:
def create_softmax(x):
    x_len = int(x.get_shape()[0])

    # create a tiled array
    # [1, 2, 3] 
    # =>
    # [[1,2,3], [1,2,3], [1,2,3]]
    x_tiled = tf.tile(tf.expand_dims(x, 0), [x_len, 1])

    # get the mask to do element-wise multiplication
    mask = tf.ones_like(x_tiled) # returns an array of the same size filled with 1
    mask = tf.matrix_band_part(mask, 0, -1) # zeros everythings except from the upper triangular part 
    mask = tf.reverse(mask, [False, True]) # reverses the y dimension

    # compute masked softmax
    exp = tf.exp(x_tiled) * mask
    sum_exp = tf.reshape(tf.reduce_sum(exp, reduction_indices=1), (-1, 1))

    x_softmax = exp / sum_exp

    return x_softmax

0

这可能对你的课程来说有点晚了,但希望它能帮到某些人。

如果你的目标只是输出一个len(input)xlen(input)数组,你可以将一个1xlen(input)张量与扩展其维度为len(input)x1的输入数组进行矩阵乘法:

input_ = tf.placeholder(tf.float32, [len(input)])
input_shape = input_.get_shape().as_list()
tfvar = tf.Variable(tf.random_normal([1,input_shape[0]], mean=0.0,
                                    stddev=.01, dtype=tf.float32))

def function(input_):
    x = tf.expand_dims(input_, axis=1) # dims = len(input)x1
    return tf.matmul(x,tfvar) # mtrx multiplication produces 3x3 mtrx

这个函数应该适用于任何一维的input_张量,并生成一个方形的len(input_)xlen(input_)张量。

如果你的目标是训练一个tensorflow变量来完全产生提供的输出,那么你可以使用损失函数和优化器来训练tfvar

desired_output = tf.constant([[0.09003057, 0.24472847, 0.66524096], 
                              [0.26894142, 0.73105858, 0.0       ], 
                              [1.0,        0.0,        0.0       ]],
                              dtype=tf.float32)

actual_output = function(input_)
loss = tf.reduce_mean(tf.square(actual_output-desired_output))
optimizer = tf.train.AdamOptimizer().minimize(loss)

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    cost, opt = sess.run([loss, optimizer], feed_dict={input_:input})

请注意,如果您想要一个更强大的培训课程,请添加偏置、非线性和更多层。

太晚了,我七月份就毕业了。 :D - user7243382

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接