基本要求:
我們將支持文件格式的任務(wù)分成兩部分:
例如, 讀取一個(gè) CSV 文件,我們使用 一個(gè)文本讀寫器, 然后是從一行文本中解析CSV數(shù)據(jù)的運(yùn)算。
Reader 是專門用來讀取文件中的記錄的。TensorFlow中內(nèi)建了一些讀寫器Op的實(shí)例:
你可以看到這些讀寫器的界面是一樣的,唯一的差異是在它們的構(gòu)造函數(shù)中。最重要的方法是 Read。 它需要一個(gè)行列參數(shù),通過這個(gè)行列參數(shù),可以在需要的時(shí)候隨時(shí)讀取文件名 (例如: 當(dāng) Read Op首次運(yùn)行,或者前一個(gè) Read` 從一個(gè)文件中讀取最后一條記錄時(shí))。它將會(huì)生成兩個(gè)標(biāo)量張量: 一個(gè)字符串和一個(gè)字符串關(guān)鍵值。
新創(chuàng)建一個(gè)名為 SomeReader 的讀寫器,需要以下步驟:
你可以把所有的 C++ 代碼放在
tensorflow/core/user_ops/some_reader_op.cc文件中. 讀取文件的代碼將被嵌入到C++ 的 ReaderBase 類的迭代中。 這個(gè) ReaderBase 類 是在 tensorflow/core/kernels/reader_base.h 中定義的。
你需要執(zhí)行以下的方法:
以上這些方法的名字后面都帶有 "Locked", 表示 ReaderBase 在調(diào)用任何一個(gè)方法之前確保獲得互斥鎖,這樣就不用擔(dān)心線程安全(雖然只保護(hù)了該類中的元素而不是全局的)。
對(duì)于 OnWorkStartedLocked, 需要打開的文件名是 current_work() 函數(shù)的返回值。此時(shí)的 ReadLocked 的數(shù)字簽名如下:
Status ReadLocked(string* key, string* value, bool* produced, bool* at_end)
如果 ReadLocked 從文件中成功讀取了一條記錄,它將更新為:
當(dāng)你在文件(EOF)末尾,設(shè)置 *at_end 為 true ,在任何情況下,都將返回 Status::OK()。 當(dāng)出現(xiàn)錯(cuò)誤的時(shí)候,只需要使用 tensorflow/core/lib/core/errors.h 中的一個(gè)輔助功能就可以簡單地返回,不需要做任何參數(shù)修改。
接下來你講創(chuàng)建一個(gè)實(shí)際的讀寫器Op。 如果你已經(jīng)熟悉了添加新的Op 那會(huì)很有幫助。 主要步驟如下:
要注冊(cè)O(shè)p,你需要用到一個(gè)調(diào)用指令定義在 tensorflow/core/framework/op.h中的REGISTER_OP。
讀寫器 Op 沒有輸入,只有 Ref(string) 類型的單輸出。它們調(diào)用 SetIsStateful(),并有一個(gè) container 字符串和 shared_name 屬性. 你可以在一個(gè) Doc 中定義配置或包含文檔的額外屬性。 例如:詳見 tensorflow/core/ops/io_ops.cc等:
#include "tensorflow/core/framework/op.h"
REGISTER_OP("TextLineReader")
.Output("reader_handle: Ref(string)")
.Attr("skip_header_lines: int = 0")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.SetIsStateful()
.Doc(R"doc(
A Reader that outputs the lines of a file delimited by '\n'.
)doc");
要定義一個(gè) OpKernel, 讀寫器可以使用定義在tensorflow/core/framework/reader_op_kernel.h中的 ReaderOpKernel 的遞減快捷方式,并運(yùn)行一個(gè)叫 SetReaderFactory 的構(gòu)造函數(shù)。 定義所需要的類之后,你需要通過 REGISTER_KERNEL_BUILDER(...) 注冊(cè)這個(gè)類。
一個(gè)沒有屬性的例子:
#include "tensorflow/core/framework/reader_op_kernel.h"
class TFRecordReaderOp : public ReaderOpKernel {
public:
explicit TFRecordReaderOp(OpKernelConstruction* context)
: ReaderOpKernel(context) {
Env* env = context->env();
SetReaderFactory([this, env]() { return new TFRecordReader(name(), env); });
}
};
REGISTER_KERNEL_BUILDER(Name("TFRecordReader").Device(DEVICE_CPU),
TFRecordReaderOp);
一個(gè)帶有屬性的例子:
#include "tensorflow/core/framework/reader_op_kernel.h"
class TextLineReaderOp : public ReaderOpKernel {
public:
explicit TextLineReaderOp(OpKernelConstruction* context)
: ReaderOpKernel(context) {
int skip_header_lines = -1;
OP_REQUIRES_OK(context,
context->GetAttr("skip_header_lines", &skip_header_lines));
OP_REQUIRES(context, skip_header_lines >= 0,
errors::InvalidArgument("skip_header_lines must be >= 0 not ",
skip_header_lines));
Env* env = context->env();
SetReaderFactory([this, skip_header_lines, env]() {
return new TextLineReader(name(), skip_header_lines, env);
});
}
};
REGISTER_KERNEL_BUILDER(Name("TextLineReader").Device(DEVICE_CPU),
TextLineReaderOp);
最后一步是添加 Python 包裝器,你需要將 tensorflow.python.ops.io_ops 導(dǎo)入到 tensorflow/python/user_ops/user_ops.py,并添加一個(gè) io_ops.ReaderBase的衍生函數(shù)。
from tensorflow.python.framework import ops
from tensorflow.python.ops import common_shapes
from tensorflow.python.ops import io_ops
class SomeReader(io_ops.ReaderBase):
def __init__(self, name=None):
rr = gen_user_ops.some_reader(name=name)
super(SomeReader, self).__init__(rr)
ops.NoGradient("SomeReader")
ops.RegisterShape("SomeReader")(common_shapes.scalar_shape)
你可以在 tensorflow/python/ops/io_ops.py中查看一些范例。
一般來說,這是一個(gè)普通的Op, 需要一個(gè)標(biāo)量字符串記錄作為輸入, 因此遵循 添加Op的說明。 你可以選擇一個(gè)標(biāo)量字符串作為輸入, 并包含在錯(cuò)誤消息中報(bào)告不正確的格式化數(shù)據(jù)。
用于解碼記錄的運(yùn)算實(shí)例:
請(qǐng)注意,使用多個(gè)Op 來解碼某個(gè)特定的記錄格式也是有效的。 例如,你有一張以字符串格式保存在 tf.train.Example 協(xié)議緩沖區(qū)的圖像文件。 根據(jù)該圖像的格式, 你可能從 tf.parse_single_example 的Op 讀取響應(yīng)輸出并調(diào)用 tf.decode_jpeg, tf.decode_png, 或者 tf.decode_raw。通過讀取 tf.decode_raw 的響應(yīng)輸出并使用tf.slice 和 tf.reshape 來提取數(shù)據(jù)是通用的方法。
原文:Custom Data Readers 翻譯:@derekshang 校對(duì):Wiki