简体   繁体   English

为什么我的张量在重塑为3D之后仍然具有等级2

[英]Why my tensor still have the rank 2 after a reshape to 3D

This is my script. 这是我的剧本。 ` `

def phi(x, b, w, B):
    z1 = tf.matmul(x,w)
    z2 = tf.cos(z1+b)
    w1 =tf.reshape(w,(1,2,1000))
    #z= tf.reshape(z2,(100,1,1000))
    z=tf.expand_dims(z2, 1)
    print(z)
    print(w1)
    phix = tf.matmul(z, tf.transpose(w1))
    phix /= tf.sqrt(float(float(int(w.get_shape()[2])) / 2.))
    #print(phix)
    phix = np.reshape(phix,(200,1000))

    return phix,B



def model(phix, B, param) :
    #return tf.matmul(tf.matmul(phix, tf.transpose(param)), B)
    one = tf.matmul(phix, param)
    return one
x2 = tf.constant(Xtr)  # variable
#xtest = tf.placeholder(tf.float32, shape=[1925, 2])  # variable

#W2 = tf.Variable(tf.zeros([784, 10]),trainable=False ,name="W2")
W2 = tf.constant(np.random.normal( loc = .0 , scale = 1./20. ,size =[2, 1000] ),name="W2")
#b2 = tf.Variable(tf.zeros([10]),trainable=False , name="b2" )
b2 = tf.Variable(tf.random_uniform(shape=[1000],dtype=tf.float64),trainable=False , name="b2")
y = tf.placeholder(tf.float64, [100, 2])
#ytest = tf.placeholder(tf.float64, [1925, 2])
B = W2

param = tf.Variable(tf.zeros(shape=[1000]))  # variable trainable
norm = tf.reduce_sum(tf.square(param)) ## attention ici c'est par ce que param est un vecteur de une dimmention 
phix, B = phi (x2,b2,W2,B)
lamda = 1.e-43 
y_ = model(phix, B,param)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_)) 


step = 0.002


opt = tf.train.AdamOptimizer(step).minimize(cost)
correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1))       
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


d = {}
evolution_train = []
evolution_cost = []
iteration = range(10000)
init = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init)
    for k in [10000] :
        for i in range(k):
            batch_ys = ytr
            #batch_xs = Xtr

            #X_train, X_test, y_train, y_test = train_test_split(batch_xs, batch_ys, test_size=0.33, random_state=42)
            p = sess.run(cost, feed_dict = { y : batch_ys })


            train_accuracy = accuracy.eval(feed_dict={y: batch_ys})
            evolution_cost.append(p)
            evolution_train.append(train_accuracy)
            #print(p)
            if i%100 == 0:
                print("step " +str(i)+ " cost " +str(p)+ " train_accuracy " +str(train_accuracy)+ " --- %s seconds --- " % (time.time() - start_time))


        d["cost for " +str(k) + " iteration"] = p

` I reshape well z but when I do phix = tf.matmul(z, tf.transpose(w1)) the following message appears : ValueError: Shapes (100, 1, 1000) and (?, ?) must have the same rank `我重整了z,但是当我执行phix = tf.matmul(z,tf​​.transpose(w1))时,出现以下消息:ValueError:形状(100,1,1000)和(?,?)必须具有相同的等级

this is the error : 这是错误:

    ValueError                                Traceback (most recent call last)
/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in merge_with(self, other)
    546       try:
--> 547         self.assert_same_rank(other)
    548         new_dims = []

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in assert_same_rank(self, other)
    592         raise ValueError(
--> 593             "Shapes %s and %s must have the same rank" % (self, other))
    594 

ValueError: Shapes (100, 1, 1000) and (?, ?) must have the same rank

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in with_rank(self, rank)
    622     try:
--> 623       return self.merge_with(unknown_shape(ndims=rank))
    624     except ValueError:

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in merge_with(self, other)
    553         raise ValueError("Shapes %s and %s are not compatible" %
--> 554                          (self, other))
    555 

ValueError: Shapes (100, 1, 1000) and (?, ?) are not compatible

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-75-1f84fec5a618> in <module>()
     33 param = tf.Variable(tf.zeros(shape=[1000]))  # variable trainable
     34 norm = tf.reduce_sum(tf.square(param)) ## attention ici c'est par ce que param est un vecteur de une dimmention
---> 35 phix, B = phi (x2,b2,W2,B)
     36 lamda = 1.e-43
     37 y_ = model(phix, B,param)

<ipython-input-75-1f84fec5a618> in phi(x, b, w, B)
      7     print(z)
      8     print(w1)
----> 9     phix = tf.matmul(z, tf.transpose(w1))
     10     phix /= tf.sqrt(float(float(int(w.get_shape()[2])) / 2.))
     11     #print(phix)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, a_is_sparse, b_is_sparse, name)
   1034                                    transpose_a=transpose_a,
   1035                                    transpose_b=transpose_b,
-> 1036                                    name=name)
   1037 
   1038 sparse_matmul = gen_math_ops._sparse_mat_mul

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py in _mat_mul(a, b, transpose_a, transpose_b, name)
    909   """
    910   return _op_def_lib.apply_op("MatMul", a=a, b=b, transpose_a=transpose_a,
--> 911                               transpose_b=transpose_b, name=name)
    912 
    913 

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    653         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    654                          input_types=input_types, attrs=attr_protos,
--> 655                          op_def=op_def)
    656         outputs = op.outputs
    657         return _Restructure(ops.convert_n_to_tensor(outputs), output_structure)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in create_op(self, op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_shapes, compute_device)
   2154                     original_op=self._default_original_op, op_def=op_def)
   2155     if compute_shapes:
-> 2156       set_shapes_for_outputs(ret)
   2157     self._add_op(ret)
   2158     self._record_op_seen_by_control_dependencies(ret)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in set_shapes_for_outputs(op)
   1610       raise RuntimeError("No shape function registered for standard op: %s"
   1611                          % op.type)
-> 1612   shapes = shape_func(op)
   1613   if len(op.outputs) != len(shapes):
   1614     raise RuntimeError(

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/common_shapes.py in matmul_shape(op)
     79 def matmul_shape(op):
     80   """Shape function for a MatMul op."""
---> 81   a_shape = op.inputs[0].get_shape().with_rank(2)
     82   transpose_a = op.get_attr("transpose_a")
     83   b_shape = op.inputs[1].get_shape().with_rank(2)

/Users/DEMANOU/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py in with_rank(self, rank)
    623       return self.merge_with(unknown_shape(ndims=rank))
    624     except ValueError:
--> 625       raise ValueError("Shape %s must have rank %d" % (self, rank))
    626 
    627   def with_rank_at_least(self, rank):

ValueError: Shape (100, 1, 1000) must have rank 2

You did phix = np.reshape(phix,(200,1000)) using numpy to do the reshape. 您使用numpy进行了phix = np.reshape(phix,(200,1000)) I think you meant to do phix = tf.reshape(phix,(200,1000)) so tensorflow does it right? 我想你打算做phix = tf.reshape(phix,(200,1000))所以张量流对吗?

Numpy doesn't get used at computation time, only tensorflow operations get used. Numpy不会在计算时使用,仅会使用tensorflow操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM