2017-06-02 5 views
0

Ich schrieb eine Funktion, die die Gramm-Matrix für Bildmerkmale der Form (1, H, W, C) berechnet. Methode, die ich geschrieben habe, ist unten:Umgang mit unbekannten Dimensionen in 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 

Zu meiner Umsetzung der Gramm Matrix Test, gibt es eine Methode:

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']) 

Wenn ich laufen gram_matrix_test() Ich erhalte eine Fehlermeldung -> Valueerror: Kann nicht konvertieren eine unbekannte Dimension für einen Tensor:?

(Der Fehler ist auf dieser Linie -> "= Gramm tf.divide (Gramm, tot_neurons)")

Debugging Ich fand heraus, dass die Form des model.extract_features() [5] ist (?,?,?, 128) und daher ist die Division nicht möglich.

Abmessungen von style_img_test sind ((1, 192, 242, 3)), wenn wir also die Sitzung ausführen, wird H, W, C aufgefüllt.

Können Sie mir bitte erklären, wie Sie das beheben können?

+0

Verwenden Sie 'tf.shape', um eine Form als ganzzahligen Tensor zu erhalten (Sie müssen auch Ihre' int() '- Umwandlung entfernen). Dies funktioniert auch dann, wenn die Form während der Graphenkonstruktion unbekannt ist (was die Information "tensor.shape" ist). –

+0

Danke @AllenLavoie, es hat funktioniert! :) – BimalGrewal

Antwort

2

Ich habe die folgenden Änderungen vorgenommen und es hat funktioniert.

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 
Verwandte Themen