我是张力流的新手.我有以下问题:
输入:浮点数列表(或动态数组.在python列表中是要使用的数据类型)输出:是一个大小为2的数组len(input)×len(input)
输入:
[1.0, 2.0, 3.0]
Run Code Online (Sandbox Code Playgroud)
输出:
[[0.09003057, 0.24472847, 0.66524096],
[0.26894142, 0.73105858, 0.0 ],
[1.0, 0.0, 0.0 ]]
Run Code Online (Sandbox Code Playgroud)
我尝试使用while循环创建函数并独立计算每一行并连接它们,但我的导师让我探索其他方法.
你能建议我如何解决这个问题吗?
小智 5
您可以通过以下方法实现此目的:
tf.nn.softmax在这里使用,因为它也会给那些零提供小的概率这是一个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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
434 次 |
| 最近记录: |