小编Ale*_*lex的帖子

在函数内部构建张量流图

我正在学习Tensorflow,并且正在尝试正确构建我的代码.我(或多或少)知道如何构建裸图或类方法图,但我想弄清楚如何最好地构造代码.我试过这个简单的例子:

def build_graph():                
     g = tf.Graph()     
     with g.as_default():                       
         a = tf.placeholder(tf.int8)
         b = tf.add(a, tf.constant(1, dtype=tf.int8))
     return g   

graph = build_graph()
with tf.Session(graph=graph) as sess:
     feed = {a: 3}      
     print(sess.run(b, feed_dict=feed))
Run Code Online (Sandbox Code Playgroud)

应该打印出来4.然而,当我这样做时,我得到错误:

Cannot interpret feed_dict key as Tensor: Tensor 
Tensor("Placeholder:0", dtype=int8) is not an element of this graph.
Run Code Online (Sandbox Code Playgroud)

我很确定这是因为函数内的占位符build_graph是私有的,但不应该with tf.Session(graph=graph)照顾它吗?在这种情况下使用feed dict有更好的方法吗?

python structure tensorflow

6
推荐指数
2
解决办法
3552
查看次数

TensorFlow 在实现逻辑回归时返回 nan

我一直在尝试按照 MNIST 示例在 TensorFlow 中实现逻辑回归,但使用来自 CSV 的数据。每行是一个样本,有 12 个维度。我的代码如下:

batch_size = 5
learning_rate = .001
x = tf.placeholder(tf.float32,[None,12])
y = tf.placeholder(tf.float32,[None,2])
W = tf.Variable(tf.zeros([12,2]))
b = tf.Variable(tf.zeros([2]))
mult = tf.matmul(x,W)
pred = tf.nn.softmax(mult+b)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

sess = tf.Session()
sess.run(tf.initialize_all_variables())
avg_cost = 0
total_batch = int(len(Xtrain)/batch_size)
for i in range(total_batch):
    batch_xs = Xtrain[i*batch_size:batch_size*i+batch_size]
    batch_ys = ytrain[i*batch_size:batch_size*i+batch_size]
    _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,y: batch_ys})
    print(c)
Run Code Online (Sandbox Code Playgroud)

Xtrain 是一个 252x10 的 numpy 数组,而 ytrain 是一个 252x2 的单热 numpy …

python numpy logistic-regression tensorflow

2
推荐指数
1
解决办法
1348
查看次数