【问题标题】:Shapes in TensorflowTensorFlow 中的形状
【发布时间】:2017-12-03 19:51:13
【问题描述】:

我是 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_of_features,) 的形式提供数据,而我需要(num_of_features,1) 才能正确使用其他功能。

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

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

错误是:

ValueError:形状必须为 2 级,但对于输入形状为 [1,3197]、[3197] 的“MatMul”(操作:“MatMul”)为 1 级。

我试图将tf.reshapeXy 一起使用以某种方式解决此问题,但它在其他地方导致了错误。

是否可以以“正确”的形状提供feed_dict={X: cur_x, y: cur_y} 中的数据?

或者正确实现这一点的方法是什么?

谢谢。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

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

    (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_shape: (3197,); w_shape: (1, 3197)。如果我添加x = tf.reshape(x, [num_of_features, 1])matmul 就可以了。但后来我有形状为 (1, 1) 的y_estim。然后我重塑它(因为y 是(1,):y_estim = tf.reshape(y_estim, [1, ])。但我得到这个错误:ValueError: Cannot feed value of shape () for Tensor 'Placeholder_1:0', which has shape '(1,)'
    • @Valeria Plz 请查看编辑后的答案,您可以使用[1],而不是[1, ] 来回复它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2018-01-10
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多