2017-01-22 84 views
7

我是tensorflow的新手。我有以下問題:Tensorflow:關於張量流功能

輸入:浮點值列表(或動態數組在Python列表是將要使用的數據類型) 輸出:是大小爲2-d陣列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

回答

5

您可以通過以下方式實現這一目標:

  1. 重複輸入數組來創建一個方陣瓷磚輸入數據
  2. 創建一個面具在左上角由那些的
  3. 使用面罩做softmax。請注意,我們不能使用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 
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 

這個功能應該推廣到任何1D 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}) 

注意,如果你想有一個更強大的培訓會議,添加偏置,非線性和更多圖層。

+0

太晚了,我7月份畢業了。 :d – MathJunkiey