关于Tensorflow模型保存与读取的问题

   日期:2020-05-14     浏览:95    评论:0    
核心提示:关于Tensorflow模型保存与读取的问题求助大神,Tensorflow构架的保存读取问题想请教一下各位大神,我用tensorflow搭建了一个神经网络,想要保存和读取神经网络的输出,看过一篇相关的代码,自己也尝试着写了一下,但是有问题,哪位大神可以解答一下应该怎么改?代码如下。import tensorflow as tfimport numpy as npimport pandas as pddef add_layer_hidden(inputs,in_size,out_size,act人工智能

关于Tensorflow模型保存与读取的问题

求助大神,Tensorflow构架的保存读取问题

想请教一下各位大神,我用tensorflow搭建了一个神经网络,想要保存和读取神经网络的输出,看过一篇相关的代码,自己也尝试着写了一下,但是有问题,哪位大神可以解答一下应该怎么改?代码如下。

import tensorflow as tf
import numpy as np
import pandas as pd

def add_layer_hidden(inputs,in_size,out_size,activation_function=None):
    weights1 = tf.Variable(tf.random_normal([in_size, out_size]),dtype=tf.float32)
    biases1 = tf.Variable(tf.zeros([1, out_size]) + 0.1,dtype=tf.float32)
    a = weights1[0]
    b = weights1[1]
    Wx_plus_b = tf.matmul(inputs, weights1) + biases1
    if activation_function == None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function( Wx_plus_b )
    return outputs,a,b
x_train = np.linspace(0,2,100,endpoint=True)    
X_t=pd.read_csv('E:/test.csv',header=0,encoding='gbk')
X=X_t.values  #生成输入X值

Xs=tf.placeholder(tf.float32,[None,2])#生成X占位符

#定义隐含层,隐含层有10个神经元
l1=add_layer_hidden(Xs,2,10,activation_function=tf.nn.sigmoid)[0]

#定义输出层,假设没有任何激活函数
def add_layer_output(inputs,in_size,out_size,activation_function=None):
    weights2 = tf.Variable(tf.random_normal([in_size, out_size]),dtype=tf.float32)
    biases2= tf.Variable(tf.zeros([1, out_size]) + 0.1,dtype=tf.float32)
    c = weights2
    Wx_plus_b = tf.matmul(inputs, weights2) + biases2
    if activation_function == None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs,c

prediction=add_layer_output(l1,10,1,activation_function=None)[0]

w11=add_layer_hidden(Xs,2,10,activation_function=tf.nn.sigmoid)[1]
w12=add_layer_hidden(Xs,2,10,activation_function=tf.nn.sigmoid)[2]
w2=add_layer_output(l1,10,1,activation_function=None)[1]
difx = tf.matmul(tf.multiply(l1*(1-l1),w11),w2)#dy/dx,dif形状[100,1],即对应点的导数值
dift = tf.matmul(tf.multiply(l1*(1-l1),w12),w2)#dy/dt,dif形状[100,1],即对应点的导数值
loss1 = tf.square(difx+dift)
loss2 = tf.square(prediction[0]-prediction[99])
loss=tf.reduce_mean(tf.reduce_sum(loss1+loss2,reduction_indices=[1]))#生成损失函数
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)#进行梯度计算以及反向传播
init=tf.global_variables_initializer()
sess = tf.InteractiveSession()

sess.run(init)

for i in range(3000):#训练50000次
    sess.run(train_step,feed_dict={Xs:X})
    if i%50 == 0:
        total_loss = sess.run(loss,feed_dict={Xs:X})
        print(total_loss)
saver = tf.train.Saver(max_to_keep=1)
saver.save(sess,'E:/my net/nn.ckpt',global_step=3000)
saver = tf.train.Saver(max_to_keep=1) #保存模型,训练一次后可以将训练过程注释掉
saver.restore(sess, 'E:/my net/nn.ckpt')  #复现保存的模型

运行后错误如下:

NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for E:/my net/nn.ckpt
[[Node: save_29/RestoreV2_6 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_save_29/Const_0_0, save_29/RestoreV2_6/tensor_names, save_29/RestoreV2_6/shape_and_slices)]]

Caused by op ‘save_29/RestoreV2_6’, defined at:
File “E:\Anaconda\envs\tensorflow\lib\site-packages\spyder\utils\ipython\start_kernel.py”, line 241, in
main()
File “E:\Anaconda\envs\tensorflow\lib\site-packages\spyder\utils\ipython\start_kernel.py”, line 237, in main
kernel.start()
File “E:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelapp.py”, line 477, in start
ioloop.IOLoop.instance().start()
File “E:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\ioloop.py”, line 177, in start
super(ZMQIOLoop, self).start()
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tornado\ioloop.py”, line 888, in start
handler_func(fd_obj, events)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py”, line 277, in null_wrapper
return fn(*args, **kwargs)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py”, line 440, in _handle_events
self._handle_recv()
File “E:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py”, line 472, in _handle_recv
self._run_callback(callback, msg)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py”, line 414, in _run_callback
callback(*args, **kwargs)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py”, line 277, in null_wrapper
return fn(*args, **kwargs)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py”, line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py”, line 235, in dispatch_shell
handler(stream, idents, msg)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py”, line 399, in execute_request
user_expressions, allow_stdin)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\ipkernel.py”, line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\ipykernel\zmqshell.py”, line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py”, line 2698, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py”, line 2808, in run_ast_nodes
if self.run_code(code, result):
File “E:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py”, line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File “”, line 1, in
runfile(‘E:/学习材料/偏微分方程与神经网络/tensorflow搭建神经网络.py’, wdir=‘E:/学习材料/偏微分方程与神经网络’)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\spyder\utils\site\sitecustomize.py”, line 710, in runfile
execfile(filename, namespace)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\spyder\utils\site\sitecustomize.py”, line 101, in execfile
exec(compile(f.read(), filename, ‘exec’), namespace)
File “E:/学习材料/偏微分方程与神经网络/tensorflow搭建神经网络.py”, line 67, in
saver = tf.train.Saver(max_to_keep=1) #保存模型,训练一次后可以将训练过程注释掉
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 1139, in init
self.build()
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 1170, in build
restore_sequentially=self._restore_sequentially)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 691, in build
restore_sequentially, reshape)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 407, in _AddRestoreOps
tensors = self.restore_op(filename_tensor, saveable, preferred_shard)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py”, line 247, in restore_op
[spec.tensor.dtype])[0])
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_io_ops.py”, line 640, in restore_v2
dtypes=dtypes, name=name)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py”, line 767, in apply_op
op_def=op_def)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py”, line 2506, in create_op
original_op=self._default_original_op, op_def=op_def)
File “E:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py”, line 1269, in init
self._traceback = _extract_stack()

NotFoundError (see above for traceback): Unsuccessful TensorSliceReader constructor: Failed to find any matching files for E:/my net/nn.ckpt
[[Node: save_29/RestoreV2_6 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_save_29/Const_0_0, save_29/RestoreV2_6/tensor_names, save_29/RestoreV2_6/shape_and_slices)]]

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
更多>相关资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服