テンソル基本:TensorFlow 2パート02


この部分ではテンソルの使い方をシェアします.テンソルは、TensorFlowライブラリの中心オブジェクトです.これらはGPUサポートを持つNDアレイを表現するために使用され、計算グラフと勾配計算を構築するように設計されている.
すべてのテンソルはPythonの数字と文字列のように不変です.テンソルの内容を更新することはできません.
基本的なテンソルを作りましょう.最初にインポートします.
import tensorflow as tf
テンテンダーの作成
スカラーは1つの値を含みます、そして、「軸」はありません.以下のように「スカラー」または「ランク0」テンソルを作成する.
# This will be an int32 tensor by default; see "dtypes" in the output.
x = tf.constant(4)
print(x)
また、形状とDType
x = tf.constant(4, shape=(1,1), dtype=tf.float32)
print(x)
ベクトルを作成するには、RACK - 1
x = tf.constant([1,2,3])
print(x)
我々はまた、マトリックス、RAK - 2で動作することができます
x = tf.constant([[1,2,3], [4,5,6]])
print(x)
3 x 3の行列は以下のように作成できます:
x = tf.ones((3,3))
print(x)
同様に、3 x 3のゼロ行列:
x = tf.zeros((3,3))
print(x)
次の対角行列を1つの対角と0の要素を作成します
x = tf.eye(3)
print(x)
また、ランダム関数を使用して行列を作成することもできます.平均0と標準偏差1を指定する乱数を持つ3 x 3正規分布行列を作成する
x = tf.random.normal((3,3), mean=0, stddev=1)
print(x)
同様に、均一分布
x = tf.random.uniform((3,3), minval=0, maxval=1)
print(x)
また、同様の通常のPythonの範囲関数を使用することもできます
x = tf.range(10)
print(x)
型式鋳造
テンソルのデータ型を変更するには、TensorFlowのキャスト関数を使用します
x = tf.cast(x, dtype=tf.float32)
print(x)
要素演算
次の2つのテンソルを作成し
x = tf.constant([1,2,3])
y = tf.constant([4,5,6])

z = tf.add(x,y)
z = x + y  # This gives the similar answer to the above
print(z)
減算操作用
z = tf.subtract(x,y)
z = x - y
print(z)
分割操作用
z = tf.divide(x,y)
z = x / y
print(z)
テンソルの乗算操作
z = tf.multiply(x,y)
z = x * y
print(z)
また、テンソルでドット製品を実行することもできます
# dot product.... 1*4 + 2*5 + 3*6
z = tf.tensordot(x,y, axes=1)
print(z)

指数関数的指数関数
z = x ** 3
print(z)
テンソルに対して行列乗算を用いることができる
# matrix multiplication (shapes must match: number of columns A = number of rows B)
x = tf.random.normal((2,2)) # 2,3
y = tf.random.normal((3,4)) # 3,4

z = tf.matmul(x,y)
z = x @ y
print(z)

索引付け、スライス処理
x = tf.constant([[1,2,3,4],[5,6,7,8]])
print(x[0])
print(x[:, 0]) # all rows, column 0
print(x[1, :]) # row 1, all columns
print(x[1,1]) # element at 1, 1

再成形
我々は、再成形することができます
x = tf.random.normal((2,3))
print(x)
x = tf.reshape(x, (3,2))
print(x)
自動的に正しい図形を決定する- 1
x = tf.reshape(x, (-1,2))
print(x)

# suble line
x = tf.reshape(x, (6))
print(x)
numpy
Numpyの使用
x = x.numpy()
print(type(x))

x = tf.convert_to_tensor(x)
print(type(x))
# -> eager tensor = evaluates operations immediately
# without building graphs
テンソル
x = tf.constant("Patrick")
print(x)

x = tf.constant(["Patrick", "Max", "Mary"])
print(x)
変数
tf.変数は、その上にopsを実行することで値を変更できるテンソルを表します.それはあなたのプログラムが操作する共有、永続的な状態を表すのに使用されます.
tfのような高水準ライブラリ.Keras使用TFモデルパラメータを格納する変数.
b = tf.Variable([[1.0, 2.0, 3.0]])
print(b)
print(type(b))