保存并加载theano变量

时间:2016-03-04 16:40:48

标签: python pickle theano

我使用theano变量来定义函数。然后我保存变量。当我加载变量theano时,它不会将其识别为之前使用的变量。

此代码:

import theano
import theano.tensor as T
from theano.misc.pkl_utils import dump,load
x = T.scalar('x')
y = x**2

f = file('temp','wb')
dump(x,f)
f.close()
del x

f = file('temp','rb')
x=load(f)
f.close()

F=theano.function([x],y)
print F(2)

生成错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)
  File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)
  File "C:/Users/jpiabrantes/Desktop/untitled6.py", line 28, in <module>
    F=theano.function([x],y)
  File "C:\Anaconda2\lib\site-packages\theano\compile\function.py", line 320, in function
    output_keys=output_keys)
  File "C:\Anaconda2\lib\site-packages\theano\compile\pfunc.py", line 479, in pfunc
    output_keys=output_keys)
  File "C:\Anaconda2\lib\site-packages\theano\compile\function_module.py", line 1776, in orig_function
    output_keys=output_keys).create(
  File "C:\Anaconda2\lib\site-packages\theano\compile\function_module.py", line 1415, in __init__
    self._check_unused_inputs(inputs, outputs, on_unused_input)
  File "C:\Anaconda2\lib\site-packages\theano\compile\function_module.py", line 1553, in _check_unused_inputs
    i.variable, err_msg))
theano.compile.function_module.UnusedInputError: theano.function was asked to create a function computing outputs given certain inputs, but the provided input variable at index 0 is not part of the computational graph needed to compute the outputs: x.
To make this error into a warning, you can pass the parameter on_unused_input='warn' to theano.function. To disable it completely, use on_unused_input='ignore'.

我还尝试使用cPickle保存/加载相同的结果。

2 个答案:

答案 0 :(得分:2)

当您从pickle加载x时,您会获得x副本,而不是原始的x。 Pickle是一个序列化协议。就其性质而言,对象的身份不能保证是相同的。

您还必须考虑pickle用于跨不同Python进程转储/加载数据,而不是在同一进程中(我没有看到在代码中使用pickle有任何好处。)

您应该做的是将x转储并加载y

dump((x, y), f)
x, y = load(f)

Pickle可以保证转储的x是&#34;链接&#34;转储到y(因此,已加载的x与加载的y相关联,并且#34;

答案 1 :(得分:0)

我认为您的输入是正确的,但 theano 声称必须使用您的功能或设置其他参数'警告''忽略'在你的功能。