首页 \ 问答 \ Tensorflow Session.Run()Tensor对象不可调用(Tensorflow Session.Run() Tensor object is not callable)

Tensorflow Session.Run()Tensor对象不可调用(Tensorflow Session.Run() Tensor object is not callable)

我有一个使用tensorflow的ptb_word训练ptb示例的rnn模型。 Bellow我有一个代码,我正在尝试打印一些示例来测试训练模型。 我收到错误TypeError: 'Tensor' object is not callable在我生成probs, state = sess.run([mtest.output_probs(), mtest._final_state], feed_dict=feed_dict)的行上运行此代码时TypeError: 'Tensor' object is not callable probs, state = sess.run([mtest.output_probs(), mtest._final_state], feed_dict=feed_dict)

究竟是什么导致了这个错误

这是代码:

import numpy as np
import os
import tensorflow as tf
from ptb_word_lm import *
from tensorflow.models.rnn.ptb import reader
from tensorflow.python.platform import gfile

data_path = "/home/usr/simple-examples/data/"
raw_data = reader.ptb_raw_data(data_path)
train_data, valid_data, test_data, vocabulary = raw_data

test_path = os.path.join(data_path, "ptb.test.txt")
word_to_id = reader._build_vocab(test_path)


eval_config = get_config()
eval_config.batch_size = 1
eval_config.num_steps = 1

sess = tf.Session()

initializer = tf.random_uniform_initializer(-eval_config.init_scale,
                                            eval_config.init_scale)
test_input = PTBInput(config=eval_config, data=test_data, name="TestInput")
with tf.variable_scope("model", reuse=None, initializer=initializer):
    mtest = PTBModel(is_training=False, config=eval_config, input_=test_input)

sess.run(tf.initialize_all_variables())

saver = tf.train.import_meta_graph('/home/usr/models/medium/model.ckpt-50979.meta')

ckpt = tf.train.get_checkpoint_state('/home/usr/models/medium/')
if ckpt and gfile.Exists(ckpt.model_checkpoint_path):
    msg = 'Reading model parameters from %s' % ckpt.model_checkpoint_path
    print(msg)
    saver.restore(sess, ckpt.model_checkpoint_path)

def pick_from_weight(weight, pows=1.0):
    weight = weight**pows
    t = np.cumsum(weight)
    s = np.sum(weight)
    return int(np.searchsorted(t, np.random.rand(1) * s))

while True:
    number_of_sentences = 10
    sentence_cnt = 0
    text = '\n'
    end_of_sentence_char = word_to_id['<eos>']
    input_char = np.array([[end_of_sentence_char]])
    state = sess.run(mtest.initial_state)
    for attr in  mtest.__dict__:
        print attr
    print 'all attributes above'
    while sentence_cnt < number_of_sentences:
        feed_dict = {mtest._input: input_char,
                     mtest.initial_state: state}

        probs, state = sess.run([mtest.output_probs(), mtest._final_state], feed_dict=feed_dict)

        print 'after state'
        sampled_char = pick_from_weight(probs[0])
        print sampled_char
        if sampled_char == end_of_sentence_char:
            text += '.\n'
            sentence_cnt += 1
        else:
            text += ' ' + id_to_word[sampled_char]
        input_char = np.array([[sampled_char]])
    print(text)
    raw_input('press any key to continue ...')

I have a rnn model trained for the ptb example with tensorflow's ptb_word. Bellow I have a code where I'm trying to print a few examples to test the model trained. I'm getting a error TypeError: 'Tensor' object is not callable when running this code on the line I make probs, state = sess.run([mtest.output_probs(), mtest._final_state], feed_dict=feed_dict)

What exactly causes this error?

here is the code:

import numpy as np
import os
import tensorflow as tf
from ptb_word_lm import *
from tensorflow.models.rnn.ptb import reader
from tensorflow.python.platform import gfile

data_path = "/home/usr/simple-examples/data/"
raw_data = reader.ptb_raw_data(data_path)
train_data, valid_data, test_data, vocabulary = raw_data

test_path = os.path.join(data_path, "ptb.test.txt")
word_to_id = reader._build_vocab(test_path)


eval_config = get_config()
eval_config.batch_size = 1
eval_config.num_steps = 1

sess = tf.Session()

initializer = tf.random_uniform_initializer(-eval_config.init_scale,
                                            eval_config.init_scale)
test_input = PTBInput(config=eval_config, data=test_data, name="TestInput")
with tf.variable_scope("model", reuse=None, initializer=initializer):
    mtest = PTBModel(is_training=False, config=eval_config, input_=test_input)

sess.run(tf.initialize_all_variables())

saver = tf.train.import_meta_graph('/home/usr/models/medium/model.ckpt-50979.meta')

ckpt = tf.train.get_checkpoint_state('/home/usr/models/medium/')
if ckpt and gfile.Exists(ckpt.model_checkpoint_path):
    msg = 'Reading model parameters from %s' % ckpt.model_checkpoint_path
    print(msg)
    saver.restore(sess, ckpt.model_checkpoint_path)

def pick_from_weight(weight, pows=1.0):
    weight = weight**pows
    t = np.cumsum(weight)
    s = np.sum(weight)
    return int(np.searchsorted(t, np.random.rand(1) * s))

while True:
    number_of_sentences = 10
    sentence_cnt = 0
    text = '\n'
    end_of_sentence_char = word_to_id['<eos>']
    input_char = np.array([[end_of_sentence_char]])
    state = sess.run(mtest.initial_state)
    for attr in  mtest.__dict__:
        print attr
    print 'all attributes above'
    while sentence_cnt < number_of_sentences:
        feed_dict = {mtest._input: input_char,
                     mtest.initial_state: state}

        probs, state = sess.run([mtest.output_probs(), mtest._final_state], feed_dict=feed_dict)

        print 'after state'
        sampled_char = pick_from_weight(probs[0])
        print sampled_char
        if sampled_char == end_of_sentence_char:
            text += '.\n'
            sentence_cnt += 1
        else:
            text += ' ' + id_to_word[sampled_char]
        input_char = np.array([[sampled_char]])
    print(text)
    raw_input('press any key to continue ...')

原文:https://stackoverflow.com/questions/42002083
更新时间:2022-07-21 11:07

最满意答案

对于统计问题:当然,它可能发生,要么您的数据噪音很小,要么在评论中提到的方案时钟奴隶。

对于分类器的导入,你可以pickle它(用pickle模块将它保存为二进制文件,然后只需在需要时加载它并对新数据使用clf.predict()方法clf.predict()

import pickle 

#Do the classification and name the fitted object clf
with open('clf.pickle', 'wb') as file :
    pickle.dump(clf,file,pickle.HIGHEST_PROTOCOL)

然后你可以加载它

import pickle 

with open('clf.pickle', 'rb') as file :
    clf =pickle.load(file)

# Now predict on the new dataframe df as 
pred = clf.predict(df.values)

For the statistic question: of course, it can happen, either your data is having little noise or the scenario Clock Slave mentioned in the comments.

For the import of the classifier, you could pickle it ( save it as a binary with the pickle module, and then just load it whenever you need it and use the clf.predict() method on the new data

import pickle 

#Do the classification and name the fitted object clf
with open('clf.pickle', 'wb') as file :
    pickle.dump(clf,file,pickle.HIGHEST_PROTOCOL)

And then later you can load it

import pickle 

with open('clf.pickle', 'rb') as file :
    clf =pickle.load(file)

# Now predict on the new dataframe df as 
pred = clf.predict(df.values)

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)