「ディープラーニングの実践」(TF2.0版)の第2章

第二章

import tensorflow as tf
print(tf.__version__)

TFのバージョンを確認してください

2.2データ操作

2.2.1テンソルを作成する

  1. テンソルを作成する
x = tf.constant(range(12))#constant 代表是常量的tensor
print(x.shape)
x
print(x)
len(x)#可以用len函数获取长度
(12,)
<tf.Tensor: id=0, shape=(12,), dtype=int32, numpy=array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])>
12
  1. reshape関数を
    使用するreshape関数を使用して、行ベクトルxの形状を(3、4)に変更します。これは、3行4列の行列であり、Xとして表します。
 X = tf.reshape(x,(3,4))#第一个参数为tensor,第二个参数为()元组

上記のx.reshape((3、4))は、x.reshape((-1、4))またはx.reshape((3、-1))と書くこともできます。xの要素の数はわかっているので、ここで-1は、要素の数と他の次元のサイズから推測できます。

  1. 各要素が0で形状が(2、3、4)のテンソルを作成します。
tf.zeros((2,3,4))
  1. 1つの要素でテンソルを作成します
tf.ones((3,4))
  1. Pythonリスト(リスト)を介して作成する必要があるテンソルの各要素の値を指定します
Y = tf.constant([[2,1,4,3],[1,2,3,4],[4,3,2,1]])
Y
<tf.Tensor: id=9, shape=(3, 4), dtype=int32, numpy=
array([[2, 1, 4, 3],
       [1, 2, 3, 4],
       [4, 3, 2, 1]])>
  1. テンソルの各要素の値をランダムに生成する必要があります。次に、形状(3、4)のテンソルを作成します。その各要素は、平均が0、標準偏差が1の正規分布からランダムにサンプリングされます。
x=tf.random.normal(shape=[3,4], mean=0, stddev=1)
print(x)

tf.Tensor(
[[-1.153268    0.6116716   0.9703915  -2.7604232 ]
 [ 0.48349026 -0.14327626  2.940394    0.98280823]
 [ 0.11714476 -1.9485139  -0.46181852 -0.23992358]], 
 shape=(3, 4), dtype=float32)

2.2.2操作

  1. 掛け算と割り算
X + Y  #这里的X,Y有相同的形状,对应元素可以相加
X * Y#对应的元素相乘
X / Y
  1. 指数計算
Y = tf.cast(Y, tf.float32)#这里先转换tensor的类型
x=tf.reshape(tf.constant(range(12)),(3,4))
print(x)
x = tf.cast(x, tf.float32)
print(tf.exp(x))
tf.Tensor(
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]], shape=(3, 4), dtype=int32)
tf.Tensor(
[[1.0000000e+00 2.7182817e+00 7.3890562e+00 2.0085537e+01]
 [5.4598152e+01 1.4841316e+02 4.0342880e+02 1.0966332e+03]
 [2.9809580e+03 8.1030840e+03 2.2026467e+04 5.9874145e+04]], shape=(3, 4), dtype=float32)

ここでキャスト型変換が必要であることに注意してください

  1. 行列乗算、行列乗算を行うmatmul関数
Y = tf.cast(Y, tf.int32)
tf.matmul(X, tf.transpose(Y))
  1. 行列の転置
tf.transpose(Y)
  1. テンソルステッチ
tf.concat([X,Y],axis = 0)#行为axis=0,结果shape (6,4)
tf.concat([X,Y],axis = 1)#列为axis=1,结果shape (3,8
  1. 判定値が等しい場合、例としてX == Yを取ります。XとYが同じ位置にあるという条件が真であると判断された場合(値が等しい場合)、同じテンソルの値は同じです。位置は1です。それ以外の場合は0です。
tf.equal(X,Y)
<tf.Tensor: id=31, shape=(3, 4), dtype=bool, numpy=
array([[False,  True, False,  True],
       [False, False, False, False],
       [False, False, False, False]])>

tf.reduce_sum(X)

2.2.3ブロードキャストメカニズム

同じ形状の2つのテンソルに対して要素ごとの操作を実行します。形状の異なる2つのテンソルに対して要素ごとの操作を実行すると、ブロードキャストメカニズムがトリガーされる場合があります。最初に要素を適切にコピーして2つのテンソルの形状を同じにし、次に要素ごとの操作を実行します。

2.2.4インデックス

テンソルでは、インデックス(インデックス)は要素の位置を表します。テンソルのインデックスは0から始まり、1つずつ増加します。たとえば、3行2列の行列には、それぞれ行インデックス0、1、2、列インデックス0、1があります。

X[1:3]
#X为3行4列,这句话等于X[1:3,:],依据左闭右开指定范围的惯例,它截取了矩阵X中行索引为1和2的两行。
<tf.Tensor: id=50, shape=(2, 4), dtype=float32, numpy=
array([[ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.]], dtype=float32)>
  1. 割り当て
    行列の行と列のインデックスなど、テンソルでアクセスする必要がある単一の要素の位置を指定し、要素を再割り当てします。
X = tf.Variable(X)#从常量转换为变量
X[1,2].assign(9)
<tf.Variable 'UnreadVariable' shape=(3, 4) dtype=float32, numpy=
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  9.,  7.],
       [ 8.,  9., 10., 11.]], dtype=float32)>

2.2.5操作メモリのオーバーヘッド

TensorとNumPyの相互変換

import numpy as np

P = np.ones((2,3))
D = tf.constant(P)

以下はTFのテンソルです

<tf.Tensor: id=115, shape=(2, 3), dtype=float64, numpy=
array([[1., 1., 1.],
       [1., 1., 1.]])>

変換して戻した後、
以下はnpテンソルです

np.array(D)

2.3自動グラデーション

ここに画像の説明を挿入xxの勾配列ベクトルに対する関数要求。

x = tf.reshape(tf.Variable(range(4), dtype=tf.float32),(4,1))

ここに画像の説明を挿入

with tf.GradientTape() as t:
    t.watch(x)
    y = 2 * tf.matmul(tf.transpose(x), x)

dy_dx = t.gradient(y, x)
dy_dx
<tf.Tensor: id=30, shape=(4, 1), dtype=float32, numpy=
array([[ 0.],
       [ 4.],
       [ 8.],
       [12.]], dtype=float32)>
with tf.GradientTape(persistent=True) as g:
    g.watch(x)
    y = x * x
    z = y * y
    dz_dx = g.gradient(z, x)  # 108.0 (4*x^3 at x = 3)
    dy_dx = g.gradient(y, x)  # 6.0
dz_dx,dy_dx
WARNING:tensorflow:Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.
WARNING:tensorflow:Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.

(<tf.Tensor: id=41, shape=(4, 1), dtype=float32, numpy=
 array([[  0.],
        [  4.],
        [ 32.],
        [108.]], dtype=float32)>,
 <tf.Tensor: id=47, shape=(4, 1), dtype=float32, numpy=
 array([[0.],
        [2.],
        [4.],
        [6.]], dtype=float32)>)
with tf.GradientTape(persistent=True) as g:
    g.watch(x)
    y = x * x
    z = y * y
    dz_dx = g.gradient(z, x)  # 108.0 (4*x^3 at x = 3)
    dy_dx = g.gradient(y, x)  # 6.0
dz_dx,dy_dx

WARNING:tensorflow:Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.
WARNING:tensorflow:Calling GradientTape.gradient on a persistent tape inside its context is significantly less efficient than calling it outside the context (it causes the gradient ops to be recorded on the tape, leading to increased CPU and memory usage). Only call GradientTape.gradient inside the context if you actually want to trace the gradient in order to compute higher order derivatives.

(<tf.Tensor: id=41, shape=(4, 1), dtype=float32, numpy=
 array([[  0.],
        [  4.],
        [ 32.],
        [108.]], dtype=float32)>,
 <tf.Tensor: id=47, shape=(4, 1), dtype=float32, numpy=
 array([[0.],
        [2.],
        [4.],
        [6.]], dtype=float32)>)

2.4

特定の関数またはクラスの特定の使用法を知りたい場合は、ヘルプ関数を使用できます。例としてones関数を使用して、その使用法を確認しましょう。詳細については、TensorflowのAPIドキュメントバージョン選択ページを使用して、クエリ用の環境のtensorflowバージョンと一致するAPIバージョンを選択できます。

help(tf.ones)

モジュールで使用できる関数とクラスを知りたい場合は、dir関数を使用できます。以下に、dtypesとランダムモジュールのすべてのメンバーまたは属性を出力します。

モジュールで使用できる関数とクラスを知りたい場合は、dir関数を使用できます。以下に、dtypesとランダムモジュールのすべてのメンバーまたは属性を出力します。

dir(tf.dtypes)

['DType',
 'QUANTIZED_DTYPES',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__path__',
 '__spec__',
 '_sys',
 'as_dtype',
 'bfloat16',
 'bool',
 'cast',
 'complex',
 'complex128',
 'complex64',
 'double',
 'float16',
 'float32',
 'float64',
 'half',
 'int16',
 'int32',
 'int64',
 'int8',
 'qint16',
 'qint32',
 'qint8',
 'quint16',
 'quint8',
 'resource',
 'saturate_cast',
 'string',
 'uint16',
 'uint32',
 'uint64',
 'uint8',
 'variant']

おすすめ

転載: blog.csdn.net/ALZFterry/article/details/113584237