Tensorflow入門 テンソルと演算

GPUが使用可能であるかどうかを確認する

print(tf.config.experimental.list_physical_devices("GPU"))

Numpy配列とtf.tensorの違い

tensorGPUに乗せられる。 tensorは変更不可

tf.data:TensorFlow入力パイプラインを構築する

分散ファイルシステムとは

複数のファイルサーバに複数のクライアントがアクセスできる。ファイルサーバはクライアント側からは統一的にアクセス可能?

Pythonのlambda式

記法

name=lambda argument1,argument2, ... :formula

具体例

list1=["tarou","hanako","kenji"]
list1_sorted=sorted(list1,key=lambda x:x[0])
print(list1_sorted)#['hanako', 'kenji', 'tarou']

tensorflowのバージョン

バグを避けるために、2.x以降であることを必ず確認する。

print(tf.__version__)

Datasetをbatchごとにまとめる

dataset = tf.data.Dataset.from_tensor_slices(tf.range(10)).batch(5)
for item in dataset:
    print(item)
#tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int32)
#tf.Tensor([5 6 7 8 9], shape=(5,), dtype=int32)

Datasetを繰り返す

dataset = tf.data.Dataset.from_tensor_slices(tf.range(3)).repeat(3)
for item in dataset:
    print(item)
#tf.Tensor(0, shape=(), dtype=int32)
#tf.Tensor(1, shape=(), dtype=int32)
#tf.Tensor(2, shape=(), dtype=int32)
#tf.Tensor(0, shape=(), dtype=int32)
#tf.Tensor(1, shape=(), dtype=int32)
#tf.Tensor(2, shape=(), dtype=int32)
#tf.Tensor(0, shape=(), dtype=int32)
#tf.Tensor(1, shape=(), dtype=int32)
#tf.Tensor(2, shape=(), dtype=int32)

チェインメソッドであることを活かした応用例

dataset = tf.data.Dataset.from_tensor_slices(tf.range(10)).repeat(3).batch(7)
for item in dataset:
    print(item)
#tf.Tensor([0 1 2 3 4 5 6], shape=(7,), dtype=int32)
#tf.Tensor([7 8 9 0 1 2 3], shape=(7,), dtype=int32)
#tf.Tensor([4 5 6 7 8 9 0], shape=(7,), dtype=int32)
#tf.Tensor([1 2 3 4 5 6 7], shape=(7,), dtype=int32)
#tf.Tensor([8 9], shape=(2,), dtype=int32)

この例では、[0,1,...9]を3つつなげた後に、7こずつ取り出している。

Datasetのシャッフル

記法は

dataset=tf.data.Dataset.from_tensor_slices(リスト).shuffle(シャッフル範囲)

リストの長さとシャッフル範囲が一致すれば完全にランダムになるから、ほとんどの場合はそうすればよいと思う。

mapによってDatasetの値を変換する

dataset = tf.data.Dataset.from_tensor_slices(tf.range(4)).map(lambda x: x**2)
for item in dataset:
    print(item)
#tf.Tensor(0, shape=(), dtype=int32)
#tf.Tensor(1, shape=(), dtype=int32)
#tf.Tensor(4, shape=(), dtype=int32)
#tf.Tensor(9, shape=(), dtype=int32)

応用例 mnistの画像を回転させる

scipy.ndimage.rotate の使い方

 scipy.ndimage.rotate(input,angle,reshape)

reshapeについて 「reshape が true の場合,入力配列が出力に完全に含まれるように出力の形状が調整されます.デフォルトはTrueです。」 とのこと。明示的にreshape=Falseにすることが多いと思う。

参考

qiita.com