numpy 我不能让函数预测工作

rmbxnbpk  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(105)
def custom_predictions(path):
    img = ig.load_img(path, target_size=(64, 64), grayscale=False, color_mode='rgb', interpolation='nearest')
    plt.imshow(img)
    img = np.expand_dims(img, axis=0)
    img.reshape(1,64,64,3)
    print(np.shape(img))
    prediction = np.argmax(model.predict(np.array(img)))
#     result=loaded_model.predict_classes(img)
    plt.title(labels[prediction])
    plt.show()



custom_predictions('Desktop/data1a/training/00-damage/0007.JPEG')

(1, 64, 64, 3)
---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 custom_predictions('Desktop/data1a/training/00-damage/0007.JPEG')

Input In [6], in custom_predictions(path)
      5     img.reshape(1,64,64,3)
      6     print(np.shape(img))
----> 7     prediction = np.argmax(model.predict(np.array(img)))
      8 #     result=loaded_model.predict_classes(img)
      9     plt.title(labels[prediction])

File ~\anaconda3\envs\tf2.5\lib\site-packages\tensorflow\python\keras\engine\training.py:1696, in Model.predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
   1690   except ValueError:
   1691     warnings.warn('Using Model.predict with '
   1692                   'MultiWorkerDistributionStrategy or TPUStrategy and '
   1693                   'AutoShardPolicy.FILE might lead to out-of-order result'
   1694                   '. Consider setting it to AutoShardPolicy.DATA.')
-> 1696 data_handler = data_adapter.get_data_handler(
   1697     x=x,
   1698     batch_size=batch_size,
   1699     steps_per_epoch=steps,
   1700     initial_epoch=0,
   1701     epochs=1,
   1702     max_queue_size=max_queue_size,
   1703     workers=workers,
   1704     use_multiprocessing=use_multiprocessing,
   1705     model=self,
   1706     steps_per_execution=self._steps_per_execution)
   1708 # Container that configures and calls `tf.keras.Callback`s.
   1709 if not isinstance(callbacks, callbacks_module.CallbackList):

字符串
文件~\anaconda3\envs\tf2.5\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py:1364,in get_data_handler(*args,**kwargs)1362 if getattr(kwargs[“model”],“_cluster_coordinator”,None):1363 return _transferterCoordinatorDataController(*args,**kwargs)-> 1364 return DataController(*args,**kwargs)

File ~\anaconda3\envs\tf2.5\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py:1150, in DataHandler.__init__(self, x, y, sample_weight, batch_size, steps_per_epoch, initial_epoch, epochs, shuffle, class_weight, max_queue_size, workers, use_multiprocessing, model, steps_per_execution, distribute)
       1148 else:
       1149   self._steps_per_execution = steps_per_execution
    -> 1150   self._steps_per_execution_value = steps_per_execution.numpy().item()
       1152 adapter_cls = select_data_adapter(x, y)
       1153 self._verify_data_adapter_compatibility(adapter_cls)
    
    File ~\anaconda3\envs\tf2.5\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py:628, in BaseResourceVariable.numpy(self)
    626 def numpy(self):
    627   if context.executing_eagerly():
--> 628     return self.read_value().numpy()
    629   raise NotImplementedError(
    630       "numpy() is only available when eager execution is enabled.")


File ~\anaconda 3\envs\tf 2.5\lib\site-packages\tensorflow\python\framework\ops.py:1094,in _AncherTensorBase.numpy(self)1071“将此Tensor的内容复制到NumPy数组或标量中。1072 1073与NumPy数组不同,Tensor是不可变的,因此此方法必须复制(...)1091 NumPy dtype. 1092“1093 # TODO(slebedev):考虑避免对非CPU或远程Tensor进行复制。-> 1094 maybe_numpy = self._numpy()# pylint:disable=protected-access 1095 return maybe_bytes.copy()if isinstance(maybe_bytes,np.ndarray)else maybe_bytes

File ~\anaconda3\envs\tf2.5\lib\site-packages\tensorflow\python\framework\ops.py:1062, in _EagerTensorBase._numpy(self)
   1060   return self._numpy_internal()
   1061 except core._NotOkStatusException as e:  # pylint: disable=protected-access
-> 1062   six.raise_from(core._status_to_exception(e.code, e.message), None)


文件:3,在raise_from(value,from_value)中
InternalError:流在完成之前没有阻止主机;已经处于错误状态

qco9c6ql

qco9c6ql1#

这里没有代码可供参考。
从错误日志中可以看出,这是您面临的问题:
“numpy()仅在启用即时执行时可用。”)
在这条线上:
prediction = np.argmax(model.predict(np.array(img)
这个问题与Tensorflow v1.x有关,现在不希望使用。
你最好切换到TF2.x,最好是最新版本。
但是,如果您仍然打算在早期的TF版本中运行代码,
如果你已经写了代码,在代码中注解这一行:

# tf.disable_v2_behavior()

字符串
否则,请更改导入包的方式:
而不是...

from keras import backend as K


用途:

import tensorflow.keras.backend as K

相关问题