你好我是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 :(得分:0)
要使用tf.matmul,输入必须是2D矩阵(否则,您可以使用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]]})