Tensorflow 张量流中没有梯度

Tensorflow 张量流中没有梯度,tensorflow,neural-network,bayesian,Tensorflow,Neural Network,Bayesian,我写了一些代码来对tensorflow中的markov随机场进行变分推断。但是它不太起作用,因为梯度不存在或者其他什么东西,所以它不会更新参数,希望能得到帮助。我的代码在这里: import tensorflow as tf import numpy as np import math as m samples = 10 #create data x_matrix = np.random.randn(5,100) #priors are 5 gaussians with mean 0 an

我写了一些代码来对tensorflow中的markov随机场进行变分推断。但是它不太起作用,因为梯度不存在或者其他什么东西,所以它不会更新参数,希望能得到帮助。我的代码在这里:

import tensorflow as tf
import numpy as np
import math as m

samples = 10
#create data

x_matrix = np.random.randn(5,100)

#priors are 5 gaussians with mean 0 and stdev 1



#construct variational family
rv = tf.placeholder(tf.float32, shape = [samples,5])
X = tf.placeholder(tf.float32, shape = [5, 100])


p_mean = tf.Variable(np.random.randn(1,5).astype(np.float32))
p_stdev = tf.Variable(np.random.lognormal(size = (1,5)).astype(np.float32))
W = tf.multiply(tf.tile(p_stdev,[samples,1]),rv) + tf.tile(p_mean,[samples,1])

#construct the computational graph

b = tf.Variable(np.random.randn())
likelihood = tf.exp(tf.matmul(W,X) + b)
posterior = tf.add(tf.log(likelihood),tf.reshape(tf.reduce_sum(tf.log((tf.map_fn(lambda x: tf.exp(-0.5*(x)**2) / ((2*m.pi)**0.5), W))),1),[10,1]))
tot_posterior_like = tf.reduce_sum(posterior, 1)
#variational family likelihood
q_like = tf.reduce_sum(tf.log((tf.map_fn(lambda x: tf.exp(-0.5*(x)**2) / ((2*m.pi)**0.5), rv))),1)

#partition function estimate
Zest = tf.reduce_mean(tot_posterior_like - q_like)

loss = tf.reduce_mean(q_like - tot_posterior_like + Zest)

optimizer = tf.train.AdamOptimizer(.01)
minimize1 = optimizer.minimize(loss)
grads = optimizer.compute_gradients(loss)

init_op = tf.global_variables_initializer()

sess = tf.Session()

sess.run(init_op)

flag = True


for each in range(3):

    if flag:
        rvinput = np.random.randn(samples,5)
        sess.run(minimize1, {rv : rvinput, X : x_matrix})
        print(sess.run(p_mean))
        print(sess.run(p_stdev))
        print(sess.run(b))
        print(sess.run(loss, {rv : rvinput, X : x_matrix}))
        print(each)
        for gv in grads:
            print(str(sess.run(gv[0])))

print(sess.run(p_mean))
print(sess.run(p_stdev))
print(sess.run(b))
sess.close()
当我运行它时,会出现以下错误:

Traceback (most recent call last):

  File "<ipython-input-26-15e721d2dae0>", line 1, in <module>
    runfile('/home/cameron/Downloads/Estimating_ERGM.py', wdir='/home/cameron/Downloads')

  File "/home/cameron/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "/home/cameron/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/cameron/Downloads/Estimating_ERGM.py", line 72, in <module>
    print(str(sess.run(gv[0])))

  File "/home/cameron/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 778, in run
    run_metadata_ptr)

  File "/home/cameron/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 969, in _run
    fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)

  File "/home/cameron/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 408, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)

  File "/home/cameron/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 227, in for_fetch
    (fetch, type(fetch)))

TypeError: Fetch argument None has invalid type <class 'NoneType'>
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
运行文件('/home/cameron/Downloads/Estimating_ERGM.py',wdir='/home/cameron/Downloads')
文件“/home/cameron/anaconda3/lib/python3.6/site-packages/spyder/utils/site/site-customize.py”,第866行,在运行文件中
execfile(文件名、命名空间)
文件“/home/cameron/anaconda3/lib/python3.6/site packages/spyder/utils/site/sitecustomize.py”,第102行,在execfile中
exec(编译(f.read(),文件名,'exec'),命名空间)
文件“/home/cameron/Downloads/assessment_ERGM.py”,第72行,在
打印(str(sess.run(gv[0]))
文件“/home/cameron/anaconda3/lib/python3.6/site packages/tensorflow/python/client/session.py”,第778行,正在运行
运行_元数据_ptr)
文件“/home/cameron/anaconda3/lib/python3.6/site packages/tensorflow/python/client/session.py”,第969行,正在运行
fetch\u handler=\u FetchHandler(self.\u图形、fetches、feed\u dict\u字符串)
文件“/home/cameron/anaconda3/lib/python3.6/site packages/tensorflow/python/client/session.py”,第408行,在__
self.\u fetch\u mapper=\u FetchMapper.for\u fetch(fetches)
文件“/home/cameron/anaconda3/lib/python3.6/site packages/tensorflow/python/client/session.py”,第227行,用于获取
(fetch,键入(fetch)))
TypeError:获取参数None的类型无效

老实说,这个错误并不困扰我,但我认为这是代码没有计算任何梯度的症状。当我在不打印渐变的情况下运行代码时,代码会运行,但不会更新参数,即参数/权重不会在每次迭代时更改。这确实是我需要修复的,因为我想构建一个更新的模型

我怀疑罪魁祸首是行刑流程:

以下是您当前的流程:

if flag:
        rvinput = np.random.randn(samples,5)
        sess.run(minimize1, {rv : rvinput, X : x_matrix})
       #rest doesn't matter
如果只运行渐变,则不会运行损失

试试这个

if flag:
        rvinput = np.random.randn(samples,5)
        loss, _ = sess.run([loss, minimize1], feed_dict = {rv : rvinput, X : x_matrix})

嘿,我以为这解决了问题,但没有。我认为问题在于当我把它拿出来的时候,梯度解决了,但是在里面有问题。我设置这个问题的方式,有一个机会(但我没有通过数学思考)是Zest使所有的梯度抵消,但是我尝试做了
tf.NotDifferentiable(“Zest”)
,但这也没有帮助。