![]() | ![]() | ![]() | ![]() |
このガイドでは、 TensorFlowの基本の概要を簡単に説明します。このドキュメントの各セクションは、より大きなトピックの概要です。各セクションの最後に、完全なガイドへのリンクがあります。
TensorFlowは、機械学習のためのエンドツーエンドのプラットフォームです。以下をサポートします。
- 多次元配列ベースの数値計算( NumPyと同様)
- GPUと分散処理
- 自動微分
- モデルの構築、トレーニング、およびエクスポート
- もっと
テンソル
TensorFlowは、 tf.Tensor
オブジェクトとして表される多次元配列またはテンソルで動作します。これが2次元テンソルです。
import tensorflow as tf
x = tf.constant([[1., 2., 3.],
[4., 5., 6.]])
print(x)
print(x.shape)
print(x.dtype)
tf.Tensor( [[1. 2. 3.] [4. 5. 6.]], shape=(2, 3), dtype=float32) (2, 3) <dtype: 'float32'>
tf.Tensor
の最も重要な属性は、そのshape
とdtype
です。
-
Tensor.shape
:各軸に沿ったテンソルのサイズを示します。 -
Tensor.dtype
:テンソル内のすべての要素のタイプを示します。
TensorFlowは、テンソルに標準の数学演算と、機械学習に特化した多くの演算を実装します。
例えば:
x + x
<tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[ 2., 4., 6.], [ 8., 10., 12.]], dtype=float32)>
5 * x
<tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[ 5., 10., 15.], [20., 25., 30.]], dtype=float32)>
x @ tf.transpose(x)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[14., 32.], [32., 77.]], dtype=float32)>
tf.concat([x, x, x], axis=0)
<tf.Tensor: shape=(6, 3), dtype=float32, numpy= array([[1., 2., 3.], [4., 5., 6.], [1., 2., 3.], [4., 5., 6.], [1., 2., 3.], [4., 5., 6.]], dtype=float32)>
tf.nn.softmax(x, axis=-1)
<tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[0.09003057, 0.24472848, 0.6652409 ], [0.09003057, 0.24472848, 0.6652409 ]], dtype=float32)>
tf.reduce_sum(x)
<tf.Tensor: shape=(), dtype=float32, numpy=21.0>
CPUで大規模な計算を実行すると、処理が遅くなる可能性があります。適切に構成されている場合、TensorFlowはGPUなどのアクセラレータハードウェアを使用して、操作を非常に迅速に実行できます。
if tf.config.list_physical_devices('GPU'):
print("TensorFlow **IS** using the GPU")
else:
print("TensorFlow **IS NOT** using the GPU")
TensorFlow **IS** using the GPUプレースホルダー16
詳細については、 Tensorガイドを参照してください。
変数
通常tf.Tensor
オブジェクトは不変です。モデルの重み(または他の可変状態)をTensorFlowに保存するには、 tf.Variable
を使用します。
var = tf.Variable([0.0, 0.0, 0.0])
var.assign([1, 2, 3])
<tf.Variable 'UnreadVariable' shape=(3,) dtype=float32, numpy=array([1., 2., 3.], dtype=float32)>
var.assign_add([1, 1, 1])
<tf.Variable 'UnreadVariable' shape=(3,) dtype=float32, numpy=array([2., 3., 4.], dtype=float32)>
詳細については、変数ガイドを参照してください。
自動微分
最急降下法および関連するアルゴリズムは、現代の機械学習の基礎です。
これを有効にするために、TensorFlowは、微積分を使用して勾配を計算する自動微分(autodiff)を実装します。通常、これを使用して、モデルの重みに対するモデルの誤差または損失の勾配を計算します。
x = tf.Variable(1.0)
def f(x):
y = x**2 + 2*x - 5
return y
f(x)
<tf.Tensor: shape=(), dtype=float32, numpy=-2.0>
x = 1.0
の場合、 y = f(x) = (1**2 + 2*1 - 5) = -2
。
yの導関数はy
y' = f'(x) = (2*x + 2) = 4
です。 TensorFlowはこれを自動的に計算できます:
with tf.GradientTape() as tape:
y = f(x)
g_x = tape.gradient(y, x) # g(x) = dy/dx
g_x
<tf.Tensor: shape=(), dtype=float32, numpy=4.0>プレースホルダー26
この簡略化された例では、単一のスカラー( x
)に関する導関数のみを取得しますが、TensorFlowは、任意の数の非スカラーテンソルに関する勾配を同時に計算できます。
詳細については、 Autodiffガイドを参照してください。
グラフとtf.function
TensorFlowは他のPythonライブラリと同じようにインタラクティブに使用できますが、TensorFlowには次のツールも用意されています。
- パフォーマンスの最適化:トレーニングと推論を高速化します。
- エクスポート:トレーニングが完了したときにモデルを保存できるようにします。
これらでは、 tf.function
を使用してpure-TensorFlowコードをPythonから分離する必要があります。
@tf.function
def my_func(x):
print('Tracing.\n')
return tf.reduce_sum(x)
tf.function
を初めて実行すると、Pythonで実行されますが、関数内で実行されたTensorFlow計算を表す完全で最適化されたグラフがキャプチャされます。
x = tf.constant([1, 2, 3])
my_func(x)
Tracing. <tf.Tensor: shape=(), dtype=int32, numpy=6>プレースホルダー29
以降の呼び出しでは、TensorFlowは最適化されたグラフのみを実行し、TensorFlow以外のステップをスキップします。以下では、 print
はPython関数であり、TensorFlow関数ではないため、 my_func
はトレースを出力しないことに注意してください。
x = tf.constant([10, 9, 8])
my_func(x)
<tf.Tensor: shape=(), dtype=int32, numpy=27>
グラフは、異なる署名( shape
とdtype
)を持つ入力には再利用できない可能性があるため、代わりに新しいグラフが生成されます。
x = tf.constant([10.0, 9.1, 8.2], dtype=tf.float32)
my_func(x)
Tracing. <tf.Tensor: shape=(), dtype=float32, numpy=27.3>
これらのキャプチャされたグラフには、次の2つの利点があります。
- 多くの場合、これらは実行を大幅に高速化します(ただし、この些細な例ではありません)。
-
tf.saved_model
を使用してこれらのグラフをエクスポートし、サーバーやモバイルデバイスなどの他のシステムで実行できます。Pythonをインストールする必要はありません。
詳細については、グラフの概要を参照してください。
モジュール、レイヤー、およびモデル
tf.Module
は、 tf.Variable
オブジェクト、およびそれらを操作するtf.function
オブジェクトを管理するためのクラスです。 tf.Module
クラスは、次の2つの重要な機能をサポートするために必要です。
-
tf.train.Checkpoint
を使用して、変数の値を保存および復元できます。これは、モデルの状態をすばやく保存および復元できるため、トレーニング中に役立ちます。 -
tf.saved_model
を使用して、tf.Variable
値とtf.function
グラフをインポートおよびエクスポートできます。これにより、モデルを作成したPythonプログラムとは独立してモデルを実行できます。
単純なtf.Module
オブジェクトをエクスポートする完全な例を次に示します。
class MyModule(tf.Module):
def __init__(self, value):
self.weight = tf.Variable(value)
@tf.function
def multiply(self, x):
return x * self.weight
mod = MyModule(3)
mod.multiply(tf.constant([1, 2, 3]))
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([3, 6, 9], dtype=int32)>
Module
を保存します:
save_path = './saved'
tf.saved_model.save(mod, save_path)
INFO:tensorflow:Assets written to: ./saved/assets 2022-01-19 02:29:48.135588: W tensorflow/python/util/util.cc:368] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.
結果のSavedModelは、それを作成したコードから独立しています。 SavedModelは、Python、他の言語バインディング、またはTensorFlowServingからロードできます。 TensorFlowLiteまたはTensorFlowJSで実行するように変換することもできます。
reloaded = tf.saved_model.load(save_path)
reloaded.multiply(tf.constant([1, 2, 3]))
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([3, 6, 9], dtype=int32)>
tf.keras.layers.Layer
クラスとtf.keras.Model
クラスはtf.Module
に基づいて構築されており、モデルの構築、トレーニング、保存のための追加機能と便利なメソッドを提供します。これらのいくつかは、次のセクションで説明します。
詳細については、モジュールの概要を参照してください。
トレーニングループ
これをすべてまとめて、基本モデルを作成し、最初からトレーニングします。
まず、いくつかのサンプルデータを作成します。これにより、2次曲線に大まかに従う点群が生成されます。
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['figure.figsize'] = [9, 6]
x = tf.linspace(-2, 2, 201)
x = tf.cast(x, tf.float32)
def f(x):
y = x**2 + 2*x - 5
return y
y = f(x) + tf.random.normal(shape=[201])
plt.plot(x.numpy(), y.numpy(), '.', label='Data')
plt.plot(x, f(x), label='Ground truth')
plt.legend();
モデルを作成します。
class Model(tf.keras.Model):
def __init__(self, units):
super().__init__()
self.dense1 = tf.keras.layers.Dense(units=units,
activation=tf.nn.relu,
kernel_initializer=tf.random.normal,
bias_initializer=tf.random.normal)
self.dense2 = tf.keras.layers.Dense(1)
def call(self, x, training=True):
# For Keras layers/models, implement `call` instead of `__call__`.
x = x[:, tf.newaxis]
x = self.dense1(x)
x = self.dense2(x)
return tf.squeeze(x, axis=1)
model = Model(64)
plt.plot(x.numpy(), y.numpy(), '.', label='data')
plt.plot(x, f(x), label='Ground truth')
plt.plot(x, model(x), label='Untrained predictions')
plt.title('Before training')
plt.legend();
プレースホルダー45基本的なトレーニングループを作成します。
variables = model.variables
optimizer = tf.optimizers.SGD(learning_rate=0.01)
for step in range(1000):
with tf.GradientTape() as tape:
prediction = model(x)
error = (y-prediction)**2
mean_error = tf.reduce_mean(error)
gradient = tape.gradient(mean_error, variables)
optimizer.apply_gradients(zip(gradient, variables))
if step % 100 == 0:
print(f'Mean squared error: {mean_error.numpy():0.3f}')
Mean squared error: 16.123 Mean squared error: 0.997 Mean squared error: 0.964 Mean squared error: 0.946 Mean squared error: 0.932 Mean squared error: 0.921 Mean squared error: 0.913 Mean squared error: 0.907 Mean squared error: 0.901 Mean squared error: 0.897
plt.plot(x.numpy(),y.numpy(), '.', label="data")
plt.plot(x, f(x), label='Ground truth')
plt.plot(x, model(x), label='Trained predictions')
plt.title('After training')
plt.legend();
プレースホルダー48これは機能していますが、一般的なトレーニングユーティリティの実装がtf.keras
モジュールで利用できることを忘れないでください。したがって、独自に作成する前に、それらを使用することを検討してください。まず、 Model.compile
メソッドとModel.fit
メソッドは、トレーニングループを実装します。
new_model = Model(64)
new_model.compile(
loss=tf.keras.losses.MSE,
optimizer=tf.optimizers.SGD(learning_rate=0.01))
history = new_model.fit(x, y,
epochs=100,
batch_size=32,
verbose=0)
model.save('./my_model')
INFO:tensorflow:Assets written to: ./my_model/assetsプレースホルダー51l10n-プレースホルダー
plt.plot(history.history['loss'])
plt.xlabel('Epoch')
plt.ylim([0, max(plt.ylim())])
plt.ylabel('Loss [Mean Squared Error]')
plt.title('Keras training progress');
詳細については、基本的なトレーニングループとKerasガイドを参照してください。