第3章回帰のための線形ニューラルネットワーク
3.2.1. Utilities3.2.1 ユーティリティ
We need a few utilities to simplify object-oriented programming in Jupyter notebooks. One of the challenges is that class definitions tend to be fairly long blocks of code. Notebook readability demands short code fragments, interspersed with explanations, a requirement incompatible with the style of programming common for Python libraries. The first utility function allows us to register functions as methods in a class after the class has been created. In fact, we can do so even after we have created instances of the class! It allows us to split the implementation of a class into multiple code blocks.
英語のヒント
Jupyterノートブックでのオブジェクト指向プログラミングを簡単にするために、いくつかのユーティリティが必要である。難しい点の一つは、クラスの定義がかなり長いコードのブロックになりがちなことである。ノートブックの読みやすさのためには、説明を挟みながらの短いコードの断片が求められるが、これはPythonのライブラリでよく見られるプログラミングの書き方とは両立しない要求である。最初のユーティリティ関数を使うと、クラスを作った後で、関数をそのクラスのメソッドとして登録できる。実は、クラスのインスタンスを作った後でさえそうできる。これにより、クラスの実装を複数のコードブロックに分けられる。
def add_to_class(Class): #@save
"""Register functions as methods in created class."""
def wrapper(obj):
setattr(Class, obj.__name__, obj)
return wrapperLet’s have a quick look at how to use it. We plan to implement a class
A with a method do. Instead of having code for both A and do in the same code block, we can first declare the class A and create an instance a.英語のヒント
使い方をざっと見てみよう。メソッド
doをもつクラスAを実装するつもりだとする。Aとdoの両方のコードを同じコードブロックに書く代わりに、まずクラスAを宣言し、インスタンスaを作ることができる。class A:
def __init__(self):
self.b = 1
a = A()Next we define the method
do as we normally would, but not in class A’s scope. Instead, we decorate this method by add_to_class with class A as its argument. In doing so, the method is able to access the member variables of A just as we would expect had it been included as part of A’s definition. Let’s see what happens when we invoke it for the instance a.英語のヒント
次に、メソッド
doをいつものように定義するが、クラスAのスコープの中ではない。代わりに、このメソッドを、クラスAを引数とするadd_to_classで修飾する。こうすると、このメソッドは、Aの定義の一部として含まれていた場合に期待されるのと同じように、Aのメンバー変数にアクセスできる。インスタンスaに対してこれを呼び出すと何が起きるかを見てみよう。@add_to_class(A)
def do(self):
print('Class attribute "b" is', self.b)
a.do()Class attribute "b" is 1The second one is a utility class that saves all arguments in a class’s
__init__ method as class attributes. This allows us to extend constructor call signatures implicitly without additional code.英語のヒント
二つ目は、クラスの
__init__メソッドのすべての引数をクラスの属性として保存するユーティリティクラスである。これにより、追加のコードなしに、コンストラクタの呼び出しシグネチャを暗黙のうちに拡張できる。class HyperParameters: #@save
"""The base class of hyperparameters."""
def save_hyperparameters(self, ignore=[]):
raise NotImplementedWe defer its implementation into Section 23.7. To use it, we define our class that inherits from
HyperParameters and calls save_hyperparameters in the __init__ method.英語のヒント
その実装は23.7節に回す。これを使うには、
HyperParametersを継承し、__init__メソッドの中でsave_hyperparametersを呼び出すクラスを定義する。# Call the fully implemented HyperParameters class saved in d2l
class B(d2l.HyperParameters):
def __init__(self, a, b, c):
self.save_hyperparameters(ignore=['c'])
print('self.a =', self.a, 'self.b =', self.b)
print('There is no self.c =', not hasattr(self, 'c'))
b = B(a=1, b=2, c=3)self.a = 1 self.b = 2
There is no self.c = TrueThe final utility allows us to plot experiment progress interactively while it is going on. In deference to the much more powerful (and complex) TensorBoard we name it
ProgressBoard. The implementation is deferred to Section 23.7. For now, let’s simply see it in action.英語のヒント
最後のユーティリティを使うと、実験の進行中にその進み具合を対話的に描画できる。はるかに強力な(そして複雑な)TensorBoardに敬意を表して、これを
ProgressBoardと名づける。実装は23.7節に回す。今はとりあえず、動いているところを見てみよう。The
draw method plots a point (x, y) in the figure, with label specified in the legend. The optional every_n smooths the line by only showing points in the figure. Their values are averaged from the neighbor points in the original figure.英語のヒント
drawメソッドは、凡例で指定したlabelを付けて、点(x, y)を図に描く。省略可能なevery_nは、図に個の点だけを示すことで線をなめらかにする。その値は、元の図の個の近傍の点を平均したものである。class ProgressBoard(d2l.HyperParameters): #@save
"""The board that plots data points in animation."""
def __init__(self, xlabel=None, ylabel=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
ls=['-', '--', '-.', ':'], colors=['C0', 'C1', 'C2', 'C3'],
fig=None, axes=None, figsize=(3.5, 2.5), display=True):
self.save_hyperparameters()
def draw(self, x, y, label, every_n=1):
raise NotImplementedIn the following example, we draw
sin and cos with a different smoothness. If you run this code block, you will see the lines grow in animation.英語のヒント
次の例では、なめらかさを変えて
sinとcosを描く。このコードブロックを実行すると、線がアニメーションで伸びていくのが見える。board = d2l.ProgressBoard('x')
for x in np.arange(0, 10, 0.1):
board.draw(x, np.sin(x), 'sin', every_n=2)
board.draw(x, np.cos(x), 'cos', every_n=10)