2016-11-23 23 views
0

你好,我在tensorflow是新的排名使我的圖,我嘗試運行,但我得到這個錯誤:你如何改變tensorflow對象

ValueError: Shape (3,) must have rank 2 

其來源於此行

tf.matmul(tf.matmul(phix, tf.transpose(param)), B) 

我檢查了我的變量phix的等級,結果是0,我不明白爲什麼,因爲它的形狀是(3,3)。這是我的劇本,請你幫助我。

import tensorflow as tf 
def phi(x, b, w, B): 
    z = tf.matmul(x,w) 
    phix = tf.cos(z) + b # attention shapes 
    phix /= tf.sqrt(float(float(int(w.get_shape()[0]))/2.)) 

    return phix, B 



def model(phix, B, param) : 
    return tf.matmul(tf.matmul(phix, tf.transpose(param)), B) 

B = tf.constant(1., shape=[1]) # constant (non trainable) 
x2 = tf.placeholder(tf.float32, shape=[3,1]) # variable 
W2 = tf.Variable(initial_value = tf.random_normal(shape=[1, 3]),trainable=False ,name="W2") 
b2 = tf.Variable(tf.random_uniform(shape=[3]),trainable=False , name="b2") 
y = tf.Variable(tf.random_uniform(shape=[3,3]),trainable=False) 
param = tf.Variable(tf.random_uniform(shape=[3])) # variable trainable 
norm = tf.sqrt(tf.reduce_sum(tf.square(param)))**2 ## attention ici c'est par ce que param est un vecteur de une dimmention 
phix, B = phi (x2,b2,W2,B) 
lamda = tf.constant(1. , shape=[3]) 
cost = tf.nn.l2_loss(y - model(phix, B, param)) + lamda * norm 

opt = tf.train.GradientDescentOptimizer(0.5).minimize(cost) 

init = tf.initialize_all_variables() 
with tf.Session() as sess: 
    sess.run(init) 

    for i in range(10): 
     sess.run(opt) 
     z4_op = sess.run(opt , feed_dict = {x2: [[1.0],[2.0],[3.0]]}) 

    print(z4_op)  

回答

0

要使用tf.matmul,輸入必須是二維矩陣(否則,可以使用tf.mul或重塑張量爲2D)。整形應該是這樣的:

def model(phix, B, param): 
    one = tf.reshape(tf.matmul(phix, tf.reshape(param, [3, 1])), [3, 1]) 
    return tf.matmul(one, tf.reshape(B, [1,1])) 

你還需要在每次執行運算時間依賴於它喂x2佔位符的值:

for i in range(10): 
    sess.run(opt, feed_dict = {x2: [[1.0],[2.0],[3.0]]}) 
    z4_op = sess.run(opt, feed_dict = {x2: [[1.0],[2.0],[3.0]]})