首页 文章

Tensorflow中的形状

提问于
浏览
0

我是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:Shape必须为2级,但对于输入形状为'MatMul'(op:'MatMul')的排名为1:[1,3197],[3197] .

我试图用 tf.reshapeXy 以某种方式解决这个问题,但它在其他地方引起了错误 .

是否有可能以"correct"形状提供 feed_dict={X: cur_x, y: cur_y} 中的数据?

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

谢谢 .

1 回答

  • 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]
    

相关问题