使用恒定初始化器时不需要指定形状?

2024-10-01 02:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试用张量流建立线性回归模型。现在,我要为权重和偏差创建变量:

w = tf.get_variable('weights', shape = None, initializer = None)
b = tf.get_variable('bias', shape = None, initializer = None)

在斯坦福大学的CS20si课程中,我读到“如果 使用常量初始化”。但这部分代码引发了:

ValueError: Shape of a new variable (weights) must be fully defined, but instead was <unknown>.

这是否意味着我应该为这些变量设置形状?我想我松了点东西。有什么建议吗?在


Tags: 模型nonegettf线性variable课程权重
1条回答
网友
1楼 · 发布于 2024-10-01 02:20:46

您应该设置形状以初始化这些变量。以logistic回归为例。在

import tensorflow as tf
x=tf.placeholder(shape=[None,5],dtype=tf.float32,name='input')
y_=tf.placeholder(shape=[None,1],dtype=tf.float32,name='label')

w=tf.Variable(tf.random_normal([5,1]),name='weights')
b=tf.Variable(tf.zeros([1]),name='bias')
y_pred=tf.nn.softmax(tf.matmul(x,w)+b)

cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))


train_op=tf.train.AdamOptimizer(0.001).minimize(cross_entropy)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    tf.global_variables_initializer().run()
    for epoch in range(1000):
        _, loss = sess.run([train_op, cross_entropy], feed_dict={x: [X_train[i]], y: [y_train[i]]})
        if (epoch % 50 == 0):
            print('Epoch: {0}, total loss={1}'.format(epoch + 1, loss))

如果像下面这样使用常量初始化,则不需要设置形状。在

^{pr2}$

相关问题 更多 >