如果使用常量初始化程序,则无需指定形状?

时间:2018-05-02 20:04:58

标签: python tensorflow regression

尝试使用tensorflow创建线性回归模型。现在,我应该为权重和偏见创建变量:

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

从斯坦福大学CS20si课程中我读到了#34;如果是,则无需指定形状 使用常量初始化"。但是这部分代码提出了:

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

这是否意味着我应该为这些变量添加形状?我认为我松了一些东西。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

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))

如果使用常量初始化如下所示,则无需设置形状。

a=tf.get_variable("my_variable", dtype=tf.int32,initializer=tf.constant([2, 3]))