Python 张量流中的形状

Python 张量流中的形状,python,tensorflow,Python,Tensorflow,我是Tensorflow的新手,在将形状(n,)与形状(n,1)组合时遇到问题 我有以下代码: if __name__ == '__main__': trainSetX, trainSetY = utils.load_train_set() # create placeholders & variables X = tf.placeholder(tf.float32, shape=(num_of_features,)) y = tf.placeholde

我是Tensorflow的新手,在将形状
(n,)
与形状
(n,1)
组合时遇到问题

我有以下代码:

if __name__ == '__main__':
    trainSetX, trainSetY = utils.load_train_set()

    # create placeholders & variables
    X = tf.placeholder(tf.float32, shape=(num_of_features,))
    y = tf.placeholder(tf.float32, shape=(1,))
    W, b = initialize_params()

    # predict y
    y_estim = linear_function(X, W, b)
    y_pred = tf.sigmoid(y_estim)

    # set the optimizer
    loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=y_pred)
    loss_mean = tf.reduce_mean(loss)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=alpha).minimize(loss_mean)

    # training phase
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        for idx in range(num_of_examples):
            cur_x, cur_y = trainSetX[idx], trainSetY[idx]
            _, c = sess.run([optimizer, loss_mean], feed_dict={X: cur_x, y: cur_y})
我试图通过每次提供一个示例来实现随机梯度下降。问题是,它似乎以
(num\u of \u features,)
的形式提供数据,而我需要
(num\u of \u features,1)
来正确使用其他函数

例如,前面给出的代码在使用此函数计算y的预测时会导致错误:

def linear_function(x, w, b):
    y_est = tf.add(tf.matmul(w, x), b)
    return y_est
错误是:

ValueError:对于输入形状为[13197]、[3197]的“MatMul”(op:'MatMul'),形状必须为秩2,但为秩1

我试图使用
tf.reformate
X
y
以某种方式解决这个问题,但它在其他地方导致了错误

是否可以将数据以“正确”的形式输入
feed_dict={X:cur_X,y:cur_y}

或者,怎样才能正确地实现这一点


谢谢。

对于矩阵乘法,您需要遵循形状规则

(a,b)*(b,c)=(a,c)

这意味着您确实需要重塑它,因为代码中的形状没有遵循它。显示重塑后出现的错误会有所帮助

希望这能给你一些提示

import tensorflow as tf

a = tf.constant([1, 2], shape=[1, 2])
b = tf.constant([7, 8], shape=[2])

print(a.shape) # => (1, 2)
print(b.shape) # => (2,)

sess = tf.Session()

# r = tf.matmul(a, b)
# print(sess.run(r)) # this gives you error

c = tf.reshape(b, [2, 1])
print(c.shape) # => (2, 1)

r = tf.matmul(a, c)
foo = tf.reshape(r, [1])
foo = sess.run(foo)
print(foo) # this gives you [23]

我知道形状的规则。问题是我的形状如下:
x_形状:(3197,);w_形:(13197)
。如果我添加
x=tf.reforme(x,[num\u of\u features,1])
,则
matmul
工作正常。但是我有形状(1,1)的
y_estim
。然后我重新塑造它(因为
y
是(1),:
y_estim=tf。重新塑造(y_estim,[1,])
。但是我得到了这个错误:
ValueError:无法为张量“占位符1:0”输入shape()的值,它有shape'(1,)
@Valeria请看编辑过的答案,你用
[1]
,而不是
[1,]