Python keras模型作为类的一部分时不起作用
所以我有一节课Python keras模型作为类的一部分时不起作用,python,keras,Python,Keras,所以我有一节课 class Trainer: def __init__(self,episodes): self.factorModel() def factorModel(self): self.model = Sequential() self.model.add(Conv2D(50, (3, 3), activation='relu', input_shape=(3,200,200),dim_ordering="th",st
class Trainer:
def __init__(self,episodes):
self.factorModel()
def factorModel(self):
self.model = Sequential()
self.model.add(Conv2D(50, (3, 3), activation='relu', input_shape=(3,200,200),dim_ordering="th",strides=4))
self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2) ))
self.model.add(Conv2D(64, (5, 5), activation='relu') )
self.model.add(MaxPooling2D(pool_size=(2, 2) ))
self.model.add(Dense(1000, activation='relu'))
self.model.add(Flatten())
self.model.add(Dense(4, activation='softmax'))
self.model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.01), metrics=['accuracy'])
def do(self,state):
self.model.predict(np.array(state))[0]
当我尝试调用do
时,我得到了类似ValueError:Tensor Tensor(“稠密_2/Softmax:0”,shape=(?,4),dtype=float32)的错误,它不是这个图的一个元素。
当我使用相同的模型和相同的配置时,当我尝试将do函数作为线程运行时,问题就出现了,但我没有将do函数作为线程运行,一切都正常
完整错误消息
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "path", line 141, in do
self.model.predict_classes(state)[0]
File "path/.local/lib/python2.7/site-packages/keras/engine/sequential.py", line 268, in predict_classes
proba = self.predict(x, batch_size=batch_size, verbose=verbose)
File "path/.local/lib/python2.7/site-packages/keras/engine/training.py", line 1456, in predict
self._make_predict_function()
File "path/.local/lib/python2.7/site-packages/keras/engine/training.py", line 378, in _make_predict_function
**kwargs)
File "path/.local/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 3009, in function
**kwargs)
File "path/.local/lib/python2.7/site-packages/tensorflow/python/keras/backend.py", line 3479, in function
return GraphExecutionFunction(inputs, outputs, updates=updates, **kwargs)
File "path/.local/lib/python2.7/site-packages/tensorflow/python/keras/backend.py", line 3142, in __init__
with ops.control_dependencies([self.outputs[0]]):
File "path/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 5426, in control_dependencies
return get_default_graph().control_dependencies(control_inputs)
File "path/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 4867, in control_dependencies
c = self.as_graph_element(c)
File "path/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3796, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "path/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3875, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 4), dtype=float32) is not an element of this graph.
我尝试了这个问题的解决方案,所以我尝试在self.factorModel()
之后调用self.model.\u make\u predict\u function()
InvalidArgumentError:Tensor conv2d_1_输入:0,在图形中找不到feed_设备或fetch_设备中指定的输入
好的,我发现了这个问题,所以可能没有办法在线程中进行预测
因此,我根据对代码的建议进行了一些更改,现在看起来如下所示:
class Trainer:
def __init__(self,episodes):
self.factorModel()
self.graph = tf.get_default_graph()
def factorModel(self):
self.model = Sequential()
self.model.add(Conv2D(50, (3, 3), activation='relu', input_shape=(3,200,200),dim_ordering="th",strides=4))
self.model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2) ))
self.model.add(Conv2D(64, (5, 5), activation='relu') )
self.model.add(MaxPooling2D(pool_size=(2, 2) ))
self.model.add(Dense(1000, activation='relu'))
self.model.add(Flatten())
self.model.add(Dense(4, activation='softmax'))
self.model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.01), metrics=['accuracy'])
def do(self,state):
with self.graph.as_default():
self.model.predict(np.array(state))[0]
结果我得到了以下错误
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "path/Desktop/marioQProject/new_class_trainer.py", line 151, in do
self.model.predict_classes(state)[0]
File "path/.local/lib/python2.7/site-packages/keras/engine/sequential.py", line 268, in predict_classes
proba = self.predict(x, batch_size=batch_size, verbose=verbose)
File "path/.local/lib/python2.7/site-packages/keras/engine/training.py", line 1462, in predict
callbacks=callbacks)
File "path/.local/lib/python2.7/site-packages/keras/engine/training_arrays.py", line 324, in predict_loop
batch_outs = f(ins_batch)
File "patha/.local/lib/python2.7/site-packages/tensorflow/python/keras/backend.py", line 3292, in __call__
run_metadata=self.run_metadata)
File "path/.local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1458, in __call__
run_metadata_ptr)
FailedPreconditionError: Error while reading resource variable conv2d_1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/conv2d_1/bias/N10tensorflow3VarE does not exist.
[[{{node conv2d_1/Reshape/ReadVariableOp}}]]
Tensorflow对多线程不是很友好,但有一个解决方法
这样做
课堂培训师:
定义初始化(自):
self.factorModel()
self.graph=tf.get_default_graph()#[1]
def do(自身、状态):
使用self.graph.as_default():#[2]
返回self.model.predict(np.array(state))[0]
def factorModel(自):
self.model=Sequential()
self.model.add(Conv2D(50,(3,3),activation='relu',input_shape=(10,10,3),strips=4))
self.model.compile(loss='classifical_crossentropy',optimizer='adam',metrics=['accurity'])
t=培训师()
def fn():
t、 do(np.zero((1,10,10,3)))
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
thread\u one=threading.thread(目标=fn)
thread_two=线程。线程(目标=fn)
线程1.start()
线程2.start()
顺便说一句,如果您不特别需要先订购频道
,那么我建议您使用TF standard频道后订购
。无论您是使用opencv直接获取图像,还是使用numpy将枕头图像转换为ndarray,默认情况下,您将获得频道最后一个
编辑
在发送到线程之前,您是否尝试过确保模型正常工作,例如
class Trainer:
def __init__(self, episodes, model, graph):
self.graph = graph
self.model = model
model = Sequential()
model.add(Conv2D(...))
.
.
.
# make sure it runs here
model.predict(np.zeros((1, 3, 200, 200)))
# if you don't need to train then try not compile first
graph = tf.get_default_graph()
trainer = Trainer(episodes, model, graph)
还有可调用模型,而不是顺序模型,如
from keras import models, layers
inp = layers.Input((200, 200, 3))
x = layers.Conv2D(50, (3, 3), activation='relu',strides=4)(inp)
x = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2) )(x)
x = layers.Conv2D(64, (5, 5), activation='relu')(x)
.
.
.
x = layers.Dense(4, activation='softmax')(x)
model = models.Model(inp, x)
请发布您的完整错误跟踪。@VivekMehta如果这很重要,请在threadInside\uuuu init\uuuuu
中调用do函数,尝试初始化self.model=None
,然后调用self.factorModel()
@YOLO我尝试了这一点,但不幸的是仍然存在同样的问题如果您正常调用它,您还会遇到问题吗,不在线程中?所以我尝试了您的解决方案,并得到以下错误failedPremissionError:error,在从容器:localhost读取资源变量conv2d_1/bias时出错。这可能意味着变量未初始化。找不到:资源localhost/conv2d\u 1/bias/N10tensorflow3VarE不存在。
我想这可能是我的环境有问题,但idk是否可以将新的回溯和代码添加到主要问题中,尤其是前面的所有内容都是最新的,我假设正常的模型.predict
也不起作用,因为您的回溯是self.model.predict\u类
。我加了一些我能想到的东西。