2017-06-02 57 views
0

我寫了一個計算形狀(1,H,W,C)圖像特徵的克矩陣的函數。方法我寫的是下面:在Tensorflow中處理未知尺寸

def calc_gram_matrix(features, normalize=True): 
    #input: features is a tensor of shape (1, Height, Width, Channels) 

    _, H, W, C = features.shape 
    matrix = tf.reshape(features, shape=[-1, int(C)]) 
    gram = tf.matmul(tf.transpose(matrix), matrix) 

    if normalize: 
    tot_neurons = H * W * C 
    gram = tf.divide(gram,tot_neurons) 

return gram 

來測試我的落實克矩陣的,有一種方法:

def gram_matrix_test(correct): 
    gram = calc_gram_matrix(model.extract_features()[5])  # 
    student_output = sess.run(gram, {model.image: style_img_test}) 
    print(style_img_test.shape) 
    error = rel_error(correct, student_output) 
    print('Maximum error is {:.3f}'.format(error)) 

gram_matrix_test(answers['gm_out']) 

當我運行gram_matrix_test()我得到一個錯誤 - > ValueError異常:無法轉換張量的未知維度:?

(該錯誤是在這條線 - > 「克= tf.divide(克,tot_neurons)」)

在調試我發現的model.extract_features形狀()[5]是(?,?,?,128),因此劃分是不可能的。的style_img_test

尺寸爲((1,192,242,3)),所以當我們運行會話H,W,C將得到填充。

你能指導我如何解決這個問題嗎?

+0

使用'tf.shape'獲得一個整形張量的形狀(你還需要刪除你的'int()'cast)。即使圖形構造過程中形狀未知(這是'tensor.shape'給出的信息),這也是有效的。 –

+0

謝謝@AllenLavoie,它工作! :) – BimalGrewal

回答

2

我做了以下更改,它工作。

def calc_gram_matrix(features, normalize=True): 
    #input: features is a tensor of shape (1, Height, Width, Channels) 

    features_shape = tf.shape(features) 
    H = features_shape[1] 
    W = features_shape[2] 
    C = features_shape[3] 

    matrix = tf.reshape(features, shape=[-1, C]) 
    gram = tf.matmul(tf.transpose(matrix), matrix) 

    if normalize: 
    tot_neurons = H * W * C 
    tot_neurons = tf.cast(tot_neurons, tf.float32) 

    gram = tf.divide(gram,tot_neurons) 

return gram