- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我使用 NCHW
数据格式在我的 GPU 上训练了一个小型 CNN,现在我想导出一个 .pb
文件,然后我可以用它在其他应用程序中进行推理.
我写了一个小的辅助函数来使用默认值调用 Tensorflow 的 freeze_graph
函数,给定一个包含检查点文件和 graph.pbtxt 的目录:
import os
import argparse
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
dir(tf.contrib) #fix for tf.contrib undefined ops bug
from tensorflow.python.tools.freeze_graph import freeze_graph
def my_freeze_graph_2(model_dir, output_node_names):
"""Extract the sub graph defined by the output nodes and convert
all its variables into constant
Args:
model_dir: the root folder containing the checkpoint state file
output_node_names: a string, containing all the output node's names,
comma separated
"""
if not tf.gfile.Exists(model_dir):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
"directory: %s" % model_dir)
if not output_node_names:
print("You need to supply the name of a node to --output_node_names.")
return -1
# We retrieve our checkpoint fullpath
checkpoint = tf.train.get_checkpoint_state(model_dir)
input_checkpoint = checkpoint.model_checkpoint_path
# We precise the file fullname of our freezed graph
absolute_model_dir = os.path.abspath(model_dir)
output_graph = os.path.join(absolute_model_dir, "frozen_model.pb")
freeze_graph(input_graph=os.path.join(model_dir, 'graph.pbtxt'),
input_saver='',
input_binary=False,
input_checkpoint=input_checkpoint,
output_node_names=output_node_names,
restore_op_name="save/restore_all",
filename_tensor_name="save/Const:0",
output_graph=output_graph,
clear_devices=True,
initializer_nodes='')
然后我有一个小脚本试图从 frozen_model.pb
构建图表来测试卡住是否有效:
import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import argparse
import tensorflow as tf
from freeze_graph import load_graph
import cv2
if __name__ == '__main__':
# Let's allow the user to pass the filename as an argument
parser = argparse.ArgumentParser()
parser.add_argument("--frozen_model_filename", default="model-multiple_starts/frozen_model.pb", type=str, help="Frozen model file to import")
args = parser.parse_args()
# We use our "load_graph" function
graph = load_graph(args.frozen_model_filename)
# We can verify that we can access the list of operations in the graph
for op in graph.get_operations():
print(op.name)
# We access the input and output nodes
x = graph.get_tensor_by_name('prefix/Reshape:0')
y = graph.get_tensor_by_name('prefix/softmax_tensor:0')
# We launch a Session
with tf.Session(graph=graph, config=tf.ConfigProto(log_device_placement=True)) as sess:
# Note: we don't nee to initialize/restore anything
# There is no Variables in this graph, only hardcoded constants
# Load an image to use as test
im = cv2.imread('57_00000000.png', cv2.IMREAD_GRAYSCALE)
im = im.T
im = im / 255 - 0.5
im = im[None,:,:,None]
y_out = sess.run(y, feed_dict={
x: im
})
print(y_out)
如果我尝试运行我的测试脚本,我会收到以下错误:
InvalidArgumentError: CPU BiasOp only supports NHWC. [[Node: prefix/conv2d/BiasAdd = BiasAdd[T=DT_FLOAT, data_format="NCHW", _device="/job:localhost/replica:0/task:0/cpu:0"](prefix/conv2d/convolution, prefix/conv2d/bias/read)]]
我尝试了不同的配置:
它们都引发相同的错误。
问题在于我要卡住的检查点具有使用 data_format='NCHW'
定义的操作。如何使用 NHWC
数据格式卡住检查点?
翻阅这些文件,我发现在 graph.pbtxt
中,对于许多操作,data_format
被硬编码为 NCHW
。我想,然后,我需要制作一个具有 NHWC
格式的新模型,有选择地从检查点加载层的权重并使用该图手动保存 .pb
文件...我假设已经有一个过程可以做到这一点,但我找不到关于这个的任何文档,也找不到示例。
尝试在 OpenCV 的 DNN 模块中导入 .pb
文件后,我发现了以下内容:
graph.pbtxt
一起卡住会导致无法使用 .pb
文件。我还没有找到确切的原因,但是将 .pb
转换为 .pbtxt
并将其与工作卡住图进行比较,文件仅在存储的值上有所不同权重和偏差常数。graph.pbtxt
一起卡住,生成一个工作卡住图。那么,检查点似乎不能在具有不同数据格式的图之间转移(即使在卡住过程中没有出现错误或警告)。
最佳答案
通常,您会希望将图形构建包装在函数中,以便您可以有条件地为预测案例重建图形,因为通常有相当多的图形从训练到预测会发生变化。正如您所发现的,NCHW
和 NWHC
版本,例如卷积层,实际上是图形原型(prototype)中的不同 Ops,并且它们以这种方式进行硬编码,因为 GPU 优化是仅适用于其中一种格式。
正确编辑图形原型(prototype)非常困难,这就是为什么大多数执行此操作的 TensorFlow 代码都遵循我上面描述的模式。在一个非常高的层次上:
def build_graph(data_format='NCHW'):
# Conditionally use proper ops based on data_format arg
training_graph = tf.Graph()
with training_graph.as_default():
build_graph(data_format='NCHW')
with tf.Session() as sess:
# train
# checkpoint session
prediction_graph = tf.Graph()
with prediction_graph.as_default():
build_graph(data_format='NHWC')
# load checkpoint
# freeze graph
请注意,tf.estimator.Estimator
框架使这变得相对容易。您可以在 model_fn
中使用 mode
参数来决定数据格式,然后使用两个不同的 input_fn
进行训练和预测,以及框架会做剩下的。你可以在这里找到一个端到端的例子:https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10_estimator/cifar10_main.py#L77 (我已经链接到相关行)
关于python - 卡住具有不同数据格式的图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014306/
我处理来自 AVFrame.data 的原始数据。此帧的像素格式为 AV_PIX_FMT_YUV420P。我想了解此数据位于哪个值范围内。 似乎 UV(在 YUV 方案中)必须在 [-128, 128
关闭。这个问题需要更多focused .它目前不接受答案。 想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post . 去年关闭。 Improve this questio
Google Web Toolkits (GWT) RPC 调用的数据格式如何以及 IsSerializable 对象如何传输。我知道 Java Serializable 传输某种二进制格式,但是 G
我打算建立一个简单的音频接口(interface)。为此,我只想知道 ASIO 驱动程序通常以哪种格式将数据传递给程序?我无法从规范中找出这一点,也无法在其他地方找到它。我不想编写自己的驱动程序,我只
我正在编写一个平滑流客户端应用程序。在服务器端(带有Media Services扩展的IIS 7)上,我有一堆ISMV和ISMA文件,这些文件是使用Expression Encoder pro 4预先
我使用 JSON.stringify 和 JQuery.ajax() 将以下 JSON 对象从 .jsp 页面传递到 java servlet: {"bin":[{"binId":"0","binDe
我有一些来自 VLM telnet 服务的数据: show media : ( 1 broadcast - 0 vod ) cam1 type : br
我们正在导出公钥和私钥。私钥将由用 Magic 编写的非 .net 软件使用。开发人员对导出 key 的格式有疑问。是否有白皮书或其他资源来解释导出数据的格式? 最佳答案 关于导出的 blob 类型的
如何在 Altair 中创建多线图? 特别是,我有一个 pandas 数据框,如下所示: Commit Author Date Week Adds
我的数据格式类似于此示例中使用的 flare.json: 我只是想知道 d3 可缩放图表使用什么函数 来获取这种格式的数据 在 flare.json 中是这样的 { name: "stuff",
我正在尝试创建一些 JSON 用于使用 Highcharts 显示图表 http://www.highcharts.com/ 我复制了他们的一个例子: http://www.highcharts.co
我被要求编写一个读取 BSDF data format defined by Zemax 的函数此类文件的示例可在以下页面找到:BSDF file example 如果可能的话,我想只使用标准的 if
我为 CoreML 将 UIImage 转换为 CVPixelBuffer,但我想更改 RGB 像素,如 R/1.5、G/2、B/2.5。 我可以使用assumingMemoryBound(to :
我正在开发一个项目,我想展示网站中的各种文件如何相互交互。我认为使用 D3 这将是一个相当简单的任务,但现在我想知道我的 json 数据是如何排列的。这是我的数据示例: { "pages" : [{
我正在使用 Apache POI 构建一些 Excel 文件,我想确保某些单元格的类型为“Number”。 我尝试了以下方法: style.setDataFormat(HSSFDataForm
我有一些具有小数属性的实体。这些实体的属性显示在我整个 UI 的多个位置。 目前我发现自己在做: litWeight.Text = person.Weight.ToString("0.00"); 无处
首先介绍三个注解: @JsonAutoDetect (method/field):作用于方法或字段,用来表明,当生成json的时候忽略有该annotation的方法或字段 @JsonIgnore 过滤
我是 Azure 的新手,一直在使用 Azure Monitor 和 AZ Sentinel 进行日志记录和分析部分。我的审核日志从 AZ VM 中托管的第三方供应商安全设备流向 Syslog VM。
我有一些代码,例如: CellStyle cs2 = wb.createCellStyle(); CellStyle cs4 = wb.createCellStyle(); cs4.setDataFo
我正在尝试提取 YourKit 的“线程” View 中显示的数据(关于线程状态;主要是当每个线程“等待”或“可运行”时)。我已使用命令行导出实用程序为其支持的所有 View 生成所有格式。 导出目录
我是一名优秀的程序员,十分优秀!