Skip to content

ClasCat® AI Research

クラスキャット – 生成 AI, AI エージェント, MCP

Menu
  • ホーム
    • ClassCat® AI Research ホーム
    • クラスキャット・ホーム
  • OpenAI API
    • OpenAI Python ライブラリ 1.x : 概要
    • OpenAI ブログ
      • GPT の紹介
      • GPT ストアの紹介
      • ChatGPT Team の紹介
    • OpenAI platform 1.x
      • Get Started : イントロダクション
      • Get Started : クイックスタート (Python)
      • Get Started : クイックスタート (Node.js)
      • Get Started : モデル
      • 機能 : 埋め込み
      • 機能 : 埋め込み (ユースケース)
      • ChatGPT : アクション – イントロダクション
      • ChatGPT : アクション – Getting started
      • ChatGPT : アクション – アクション認証
    • OpenAI ヘルプ : ChatGPT
      • ChatGPTとは何ですか?
      • ChatGPT は真実を語っていますか?
      • GPT の作成
      • GPT FAQ
      • GPT vs アシスタント
      • GPT ビルダー
    • OpenAI ヘルプ : ChatGPT > メモリ
      • FAQ
    • OpenAI ヘルプ : GPT ストア
      • 貴方の GPT をフィーチャーする
    • OpenAI Python ライブラリ 0.27 : 概要
    • OpenAI platform
      • Get Started : イントロダクション
      • Get Started : クイックスタート
      • Get Started : モデル
      • ガイド : GPT モデル
      • ガイド : 画像生成 (DALL·E)
      • ガイド : GPT-3.5 Turbo 対応 微調整
      • ガイド : 微調整 1.イントロダクション
      • ガイド : 微調整 2. データセットの準備 / ケーススタディ
      • ガイド : 埋め込み
      • ガイド : 音声テキスト変換
      • ガイド : モデレーション
      • ChatGPT プラグイン : イントロダクション
    • OpenAI Cookbook
      • 概要
      • API 使用方法 : レート制限の操作
      • API 使用方法 : tiktoken でトークンを数える方法
      • GPT : ChatGPT モデルへの入力をフォーマットする方法
      • GPT : 補完をストリームする方法
      • GPT : 大規模言語モデルを扱う方法
      • 埋め込み : 埋め込みの取得
      • GPT-3 の微調整 : 分類サンプルの微調整
      • DALL-E : DALL·E で 画像を生成して編集する方法
      • DALL·E と Segment Anything で動的マスクを作成する方法
      • Whisper プロンプティング・ガイド
  • Gemini API
    • Tutorials : クイックスタート with Python (1) テキスト-to-テキスト生成
    • (2) マルチモーダル入力 / 日本語チャット
    • (3) 埋め込みの使用
    • (4) 高度なユースケース
    • クイックスタート with Node.js
    • クイックスタート with Dart or Flutter (1) 日本語動作確認
    • Gemma
      • 概要 (README)
      • Tutorials : サンプリング
      • Tutorials : KerasNLP による Getting Started
  • Keras 3
    • 新しいマルチバックエンド Keras
    • Keras 3 について
    • Getting Started : エンジニアのための Keras 入門
    • Google Colab 上のインストールと Stable Diffusion デモ
    • コンピュータビジョン – ゼロからの画像分類
    • コンピュータビジョン – 単純な MNIST convnet
    • コンピュータビジョン – EfficientNet を使用した微調整による画像分類
    • コンピュータビジョン – Vision Transformer による画像分類
    • コンピュータビジョン – 最新の MLPモデルによる画像分類
    • コンピュータビジョン – コンパクトな畳込み Transformer
    • Keras Core
      • Keras Core 0.1
        • 新しいマルチバックエンド Keras (README)
        • Keras for TensorFlow, JAX, & PyTorch
        • 開発者ガイド : Getting started with Keras Core
        • 開発者ガイド : 関数型 API
        • 開発者ガイド : シーケンシャル・モデル
        • 開発者ガイド : サブクラス化で新しい層とモデルを作成する
        • 開発者ガイド : 独自のコールバックを書く
      • Keras Core 0.1.1 & 0.1.2 : リリースノート
      • 開発者ガイド
      • Code examples
      • Keras Stable Diffusion
        • 概要
        • 基本的な使い方 (テキスト-to-画像 / 画像-to-画像変換)
        • 混合精度のパフォーマンス
        • インペインティングの簡易アプリケーション
        • (参考) KerasCV – Stable Diffusion を使用した高性能画像生成
  • TensorFlow
    • TF 2 : 初級チュートリアル
    • TF 2 : 上級チュートリアル
    • TF 2 : ガイド
    • TF 1 : チュートリアル
    • TF 1 : ガイド
  • その他
    • 🦜️🔗 LangChain ドキュメント / ユースケース
    • Stable Diffusion WebUI
      • Google Colab で Stable Diffusion WebUI 入門
      • HuggingFace モデル / VAE の導入
      • LoRA の利用
    • Diffusion Models / 拡散モデル
  • クラスキャット
    • 会社案内
    • お問合せ
    • Facebook
    • ClassCat® Blog
Menu

TensorFlow 2.4 : ガイド : 基本 – Tensor へのイントロダクション

Posted on 12/22/202005/25/2021 by Sales Information

TensorFlow 2.4 : ガイド : 基本 – Tensor へのイントロダクション (翻訳/解説)

翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/22/2020

* 本ページは、TensorFlow org サイトの Guide – TensorFlow Basics の以下のページを翻訳した上で
適宜、補足説明したものです:

  • Introduction to Tensors

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

★ 無料セミナー実施中 ★ クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマにウェビナー (WEB セミナー) を定期的に開催しています。スケジュールは弊社 公式 Web サイト でご確認頂けます。
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
  • Windows PC のブラウザからご参加が可能です。スマートデバイスもご利用可能です。
クラスキャットは人工知能・テレワークに関する各種サービスを提供しております :

人工知能研究開発支援 人工知能研修サービス テレワーク & オンライン授業を支援
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。

◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/
Facebook: https://www.facebook.com/ClassCatJP/

 

 

ガイド : 基本 – Tensor へのイントロダクション

import tensorflow as tf
import numpy as np

Tensor は (dtype と呼ばれる) 一様な型を持つ多次元配列です。tf.dtypes.DType で総てのサポートされる dtype を見ることができます。

NumPy に馴染みがあるならば、tensor は (一種の) np.arrays のようなものです。

総ての tensor は Python 数字と文字列のようにイミュータブルです : tensor の内容を決して更新できません、新しい一つを作成するだけです。

 

基本

幾つかの基本的な tensor を作成しましょう。

ここに スカラー or ランク-0 tensor があります。スカラーは単一の値を含みます、そして 軸 (= axes) は含みません。

# This will be an int32 tensor by default; see "dtypes" below.
rank_0_tensor = tf.constant(4)
print(rank_0_tensor)
tf.Tensor(4, shape=(), dtype=int32)

ベクトル or ランク-1 tensor は値のリストのようなものです。ベクトルは 1-軸を持ちます :

# Let's make this a float tensor.
rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
print(rank_1_tensor)
tf.Tensor([2. 3. 4.], shape=(3,), dtype=float32)

行列 or ランク-2 tensor は 2-軸を持ちます :

# If you want to be specific, you can set the dtype (see below) at creation time
rank_2_tensor = tf.constant([[1, 2],
                             [3, 4],
                             [5, 6]], dtype=tf.float16)
print(rank_2_tensor)
tf.Tensor(
[[1. 2.]
 [3. 4.]
 [5. 6.]], shape=(3, 2), dtype=float16)

スカラー, shape: []

ベクトル, shape: [3]

行列, shape: [3, 2]


tensor はより多くの軸を持つかもしれません、ここに 3-軸を持つ tensor があります :

# There can be an arbitrary number of
# axes (sometimes called "dimensions")
rank_3_tensor = tf.constant([
  [[0, 1, 2, 3, 4],
   [5, 6, 7, 8, 9]],
  [[10, 11, 12, 13, 14],
   [15, 16, 17, 18, 19]],
  [[20, 21, 22, 23, 24],
   [25, 26, 27, 28, 29]],])

print(rank_3_tensor)
tf.Tensor(
[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]]

 [[10 11 12 13 14]
  [15 16 17 18 19]]

 [[20 21 22 23 24]
  [25 26 27 28 29]]], shape=(3, 2, 5), dtype=int32)

2-軸より多くを持つ tensor を可視化するかもしれない多くの方法があります。

3-軸 tensor, shape: [3, 2, 5]


np.array か tensor.numpy を使用して tensor を NumPy 配列に変換することができます :

np.array(rank_2_tensor)
array([[1., 2.],
       [3., 4.],
       [5., 6.]], dtype=float16)
rank_2_tensor.numpy()
array([[1., 2.],
       [3., 4.],
       [5., 6.]], dtype=float16)

tensor はしばしば float と int を含みますが、以下を含む多くの他の型を持ちます :

  • 複素数
  • 文字列

基底 tf.Tensor クラスは tensor が 矩形 (= rectangular) であることを要求します — つまり、各軸に沿って、総ての要素が同じサイズであることです。けれども、異なる shape を処理できる特別なタイプの tensor があります :

  • Ragged tensors (下の RaggedTensor 参照)
  • スパース tensors (下の SparseTensor 参照)

加算、要素単位の乗算、そして行列乗算を含む、tensor 上の基本的な math を行なうことができます。

a = tf.constant([[1, 2],
                 [3, 4]])
b = tf.constant([[1, 1],
                 [1, 1]]) # Could have also said `tf.ones([2,2])`

print(tf.add(a, b), "\n")
print(tf.multiply(a, b), "\n")
print(tf.matmul(a, b), "\n")
tf.Tensor(
[[2 3]
 [4 5]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[3 3]
 [7 7]], shape=(2, 2), dtype=int32) 
print(a + b, "\n") # element-wise addition
print(a * b, "\n") # element-wise multiplication
print(a @ b, "\n") # matrix multiplication
tf.Tensor(
[[2 3]
 [4 5]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[3 3]
 [7 7]], shape=(2, 2), dtype=int32) 

tensor は総ての種類の演算 (ops) で使用されます :

c = tf.constant([[4.0, 5.0], [10.0, 1.0]])

# Find the largest value
print(tf.reduce_max(c))
# Find the index of the largest value
print(tf.argmax(c))
# Compute the softmax
print(tf.nn.softmax(c))
tf.Tensor(10.0, shape=(), dtype=float32)
tf.Tensor([1 0], shape=(2,), dtype=int64)
tf.Tensor(
[[2.6894143e-01 7.3105860e-01]
 [9.9987662e-01 1.2339458e-04]], shape=(2, 2), dtype=float32)

 

shape について

tensor は shape を持ちます。幾つかの語彙 :

  • Shape: tensor の各々の次元の長さ (要素の数)。
  • ランク: tensor 次元の数。スカラーはランク 0、ベクトルはランク 1、行列はランク 2 を持ちます。
  • 軸 or 次元: tensor の特定の次元
  • サイズ: tensor の項目の総数、shape ベクトルの積。

Note: 「2 次元の tensor」への言及を見るかもしれませんが、通常はランク-2 tensor は 2D 空間を記述しません。

tensor と tf.TensorShape オブジェクトはこれらにアクセスするための便利なプロパティを持ちます :

rank_4_tensor = tf.zeros([3, 2, 4, 5])

ランク-4 tensor, shape: [3, 2, 4, 5]


print("Type of every element:", rank_4_tensor.dtype)
print("Number of dimensions:", rank_4_tensor.ndim)
print("Shape of tensor:", rank_4_tensor.shape)
print("Elements along axis 0 of tensor:", rank_4_tensor.shape[0])
print("Elements along the last axis of tensor:", rank_4_tensor.shape[-1])
print("Total number of elements (3*2*4*5): ", tf.size(rank_4_tensor).numpy())
Type of every element: 
Number of dimensions: 4
Shape of tensor: (3, 2, 4, 5)
Elements along axis 0 of tensor: 3
Elements along the last axis of tensor: 5
Total number of elements (3*2*4*5):  120

軸はしばしばそれらのインデックスにより参照されますが、常に各々の意味を追跡するべきです。しばしば軸はグルーバルからローカルに順序付けられます : バッチ軸が最初で、続いて空間次元、そして最後に各位置のための特徴です。このように特徴ベクトルはメモリの連続的な領域です。

典型的な軸順序

 

インデキシング

単一軸インデキシング

TensorFlow は Python のリストや文字列のインデキシング に類似した、標準的な Python インデクシング・ルールと、NumPy インデキシングのための基本的なルールに従います。

  • インデックスは 0 で始まります。
  • 負のインデックスは最後から反対にカウントします。
  • コロン, :, はスライスのために使用されます: start:stop:step
rank_1_tensor = tf.constant([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
print(rank_1_tensor.numpy())
[ 0  1  1  2  3  5  8 13 21 34]

スカラーを持つインデキシングは次元を除去します :

print("First:", rank_1_tensor[0].numpy())
print("Second:", rank_1_tensor[1].numpy())
print("Last:", rank_1_tensor[-1].numpy())
First: 0
Second: 1
Last: 34

: スライスを持つインデキシングは次元を保持します :

print("Everything:", rank_1_tensor[:].numpy())
print("Before 4:", rank_1_tensor[:4].numpy())
print("From 4 to the end:", rank_1_tensor[4:].numpy())
print("From 2, before 7:", rank_1_tensor[2:7].numpy())
print("Every other item:", rank_1_tensor[::2].numpy())
print("Reversed:", rank_1_tensor[::-1].numpy())
Everything: [ 0  1  1  2  3  5  8 13 21 34]
Before 4: [0 1 1 2]
From 4 to the end: [ 3  5  8 13 21 34]
From 2, before 7: [1 2 3 5 8]
Every other item: [ 0  1  3  8 21]
Reversed: [34 21 13  8  5  3  2  1  1  0]

 

複数軸インデキシング

より高位ランク tensor は複数のインデックスを渡すことによりインデックスされます。

単一軸の場合と正確に同じルールが各軸に独立に適用されます。

print(rank_2_tensor.numpy())
[[1. 2.]
 [3. 4.]
 [5. 6.]]

各インデックスのために整数を渡すと結果はスカラーです。

# Pull out a single value from a 2-rank tensor
print(rank_2_tensor[1, 1].numpy())
4.0

整数とスライスの任意の組合せを使用してインデックスできます :

# Get row and column tensors
print("Second row:", rank_2_tensor[1, :].numpy())
print("Second column:", rank_2_tensor[:, 1].numpy())
print("Last row:", rank_2_tensor[-1, :].numpy())
print("First item in last column:", rank_2_tensor[0, -1].numpy())
print("Skip the first row:")
print(rank_2_tensor[1:, :].numpy(), "\n")
Second row: [3. 4.]
Second column: [2. 4. 6.]
Last row: [5. 6.]
First item in last column: 2.0
Skip the first row:
[[3. 4.]
 [5. 6.]] 

ここに 3-軸 tensor の例があります :

print(rank_3_tensor[:, :, 4])
tf.Tensor(
[[ 4  9]
 [14 19]
 [24 29]], shape=(3, 2), dtype=int32)

バッチの各サンプルの総ての位置に渡る最後の特徴を選択する


 

Shape を操作する

tensor の reshape は大変有用です。

# Shape returns a `TensorShape` object that shows the size on each dimension
x = tf.constant([[1], [2], [3]])
print(x.shape)
(3, 1)
# You can convert this object into a Python list, too
print(x.shape.as_list())
[3, 1]

tensor を新しい shape に reshape できます。tf.reshape 演算は高速で安価です、何故ならば基礎的なデータは複製される必要がないからです。

# You can reshape a tensor to a new shape.
# Note that you're passing in a list
reshaped = tf.reshape(x, [1, 3])
print(x.shape)
print(reshaped.shape)
(3, 1)
(1, 3)

データはメモリでそのレイアウトを保持してリクエストされた shape で新しい tensor が作成されます、同じデータをポイントして。TensorFlow は C-スタイルの 行優先 (= row-major) メモリ順序を使用します、そこではメモリの単一ステップに相当する右端のインデックスをインクリメントします。

print(rank_3_tensor)
tf.Tensor(
[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]]

 [[10 11 12 13 14]
  [15 16 17 18 19]]

 [[20 21 22 23 24]
  [25 26 27 28 29]]], shape=(3, 2, 5), dtype=int32)

tensor を平坦化すればそれがメモリでどのような順序で置かれているかを見ることができます。

# A `-1` passed in the `shape` argument says "Whatever fits".
print(tf.reshape(rank_3_tensor, [-1]))
tf.Tensor(
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29], shape=(30,), dtype=int32)

典型的には tf.reshape の唯一の合理的な使用は隣接する軸を結合するか分割することです (あるいは 1 を追加/除去)。

この 3x2x5 tensor については、(3×2)x5 か 3x(2×5) への reshape は両者とも行なうに合理的なことです、何故ならばスライスが混ざらないからです :

print(tf.reshape(rank_3_tensor, [3*2, 5]), "\n")
print(tf.reshape(rank_3_tensor, [3, -1]))
tf.Tensor(
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]
 [25 26 27 28 29]], shape=(6, 5), dtype=int32) 

tf.Tensor(
[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]
 [20 21 22 23 24 25 26 27 28 29]], shape=(3, 10), dtype=int32)

Some good reshapes.


reshape は要素の同じ総数を持つ任意の新しい shape に対して「動作します」が、軸の順序を尊重しなければそれは有用なことは何も行ないません。

tf.reshape で軸のスワッピングは動作しません、そのためには tf.transpose が必要です。

# Bad examples: don't do this

# You can't reorder axes with reshape.
print(tf.reshape(rank_3_tensor, [2, 3, 5]), "\n") 

# This is a mess
print(tf.reshape(rank_3_tensor, [5, 6]), "\n")

# This doesn't work at all
try:
  tf.reshape(rank_3_tensor, [7, -1])
except Exception as e:
  print(f"{type(e).__name__}: {e}")
tf.Tensor(
[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]]

 [[15 16 17 18 19]
  [20 21 22 23 24]
  [25 26 27 28 29]]], shape=(2, 3, 5), dtype=int32) 

tf.Tensor(
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]], shape=(5, 6), dtype=int32) 

InvalidArgumentError: Input to reshape is a tensor with 30 values, but the requested shape requires a multiple of 7 [Op:Reshape]

Some bad reshapes.


完全には指定されていない (= not-fully-specified) shape に渡り実行しても良いです。shape が None を含む (次元の長さが未知) か shape が None (tensor のランクが未知) (の場合) です。

tf.RaggedTensor を除けば、そのような shape は TensorFlow のシンボリックな、グラフ構築 API のコンテキストでだけ発生します。

  • tf.function
  • keras functional API

 

More on DTypes

tf.Tensor のデータ型を調べるには Tensor.dtype プロパティを使用します。

Python オブジェクトから tf.Tensor を作成するときオプションでデータ型を指定しても良いです。

そうしない場合、TensorFlow はデータを表せるデータ型を選択します。TensorFlow は Python 整数を tf.int32 に Python 浮動小数点数を tf.float32 に変換します。さもなければ TensorFlow は NumPy が配列に変換するときに使用する同じルールを使用します。

型から型へキャストできます。

the_f64_tensor = tf.constant([2.2, 3.3, 4.4], dtype=tf.float64)
the_f16_tensor = tf.cast(the_f64_tensor, dtype=tf.float16)
# Now, cast to an uint8 and lose the decimal precision
the_u8_tensor = tf.cast(the_f16_tensor, dtype=tf.uint8)
print(the_u8_tensor)
tf.Tensor([2 3 4], shape=(3,), dtype=uint8)

 

ブロードキャスト

ブロードキャストは NumPy の同値な特徴 から借りた概念です。短く言えば、ある条件下で、より小さい tensor がより大きい tensor に適合するために (それらの上で結び付いた演算を実行するとき) 自動的に「ストレッチ」されることです。

最も単純で一般的なケースはスカラーに tensor を乗算か加算することを試みるときです。その場合、スカラーは他の引数と同じ shape になるようにブロードキャストされます。

x = tf.constant([1, 2, 3])

y = tf.constant(2)
z = tf.constant([2, 2, 2])
# All of these are the same computation
print(tf.multiply(x, 2))
print(x * y)
print(x * z)
tf.Tensor([2 4 6], shape=(3,), dtype=int32)
tf.Tensor([2 4 6], shape=(3,), dtype=int32)
tf.Tensor([2 4 6], shape=(3,), dtype=int32)

同様に、1-sized 次元は他の引数に適合するようにストレッチできます。両者の引数は同じ計算でストレッチできます。

この場合 3×1 行列は 3×4 行列を生成するために 1×4 行列により要素単位で乗算されます。leading 1 がどのようにオプションであるかに注意してください : y の shape は [4] です。

# These are the same computations
x = tf.reshape(x,[3,1])
y = tf.range(1, 5)
print(x, "\n")
print(y, "\n")
print(tf.multiply(x, y))
tf.Tensor(
[[1]
 [2]
 [3]], shape=(3, 1), dtype=int32) 

tf.Tensor([1 2 3 4], shape=(4,), dtype=int32) 

tf.Tensor(
[[ 1  2  3  4]
 [ 2  4  6  8]
 [ 3  6  9 12]], shape=(3, 4), dtype=int32)

A broadcasted add: [3, 1] 掛ける [1, 4] は [3,4] を与えます

ここにブロードキャストなしの同じ演算があります :

x_stretch = tf.constant([[1, 1, 1, 1],
                         [2, 2, 2, 2],
                         [3, 3, 3, 3]])

y_stretch = tf.constant([[1, 2, 3, 4],
                         [1, 2, 3, 4],
                         [1, 2, 3, 4]])

print(x_stretch * y_stretch)  # Again, operator overloading
tf.Tensor(
[[ 1  2  3  4]
 [ 2  4  6  8]
 [ 3  6  9 12]], shape=(3, 4), dtype=int32)

大抵の場合、ブロードキャストは時間と空間の両者で効率的です、何故ならばブロードキャスト演算はメモリ内で膨張した tensor を決して具現化しないからです。

tf.broadcast_to を使用してブロードキャストがどのように見えるかを見ます。

print(tf.broadcast_to(tf.constant([1, 2, 3]), [3, 3]))
tf.Tensor(
[[1 2 3]
 [1 2 3]
 [1 2 3]], shape=(3, 3), dtype=int32)

例えば、数学的 op とは違い、broadcast_to はメモリを節約するための特別なことは何もしません。ここでは、tensor を具現化しています。

それは更に複雑でさえあり得ます。Jake VanderPlas の書籍 Python Data Science Handbook の このセクション はより多くのブロードキャスト・トリックを示します (再び NumPy で)。

 

tf.convert_to_tensor

tf.matmul と tf.reshape のような殆どの ops はクラス tf.Tensor の引数を取ります。けれども、上のケースで tensor のように shape された Python オブジェクトは受け取られることに気付くでしょう。

殆どの、しかし総てではない、ops は非-tensor 引数上で convert_to_tensor を呼び出します。変換のレジストリがあり、そしてNumPy の ndarray, TensorShape, Python リストと tf.Variable のような殆どのオブジェクト・クラスは総て自動的に変換します。

更なる詳細については tf.register_tensor_conversion_function を見てください、そして貴方自身の型を持つ場合には自動的に tensor に変換したいでしょう。

 

Ragged Tensors

ある軸に沿って可変な数の要素を持つ tensor は ragged と呼ばれます。ragged データのためには tf.ragged.RaggedTensor を使用します。

例えば、これは通常の tensor としては表すことができません :

tf.RaggedTensor, shape: [4, None]


ragged_list = [
    [0, 1, 2, 3],
    [4, 5],
    [6, 7, 8],
    [9]]
try:
  tensor = tf.constant(ragged_list)
except Exception as e:
  print(f"{type(e).__name__}: {e}")
ValueError: Can't convert non-rectangular Python sequence to Tensor.

代わりに tf.ragged.constant を使用して tf.RaggedTensor を作成します :

ragged_tensor = tf.ragged.constant(ragged_list)
print(ragged_tensor)
<tf.RaggedTensor [[0, 1, 2, 3], [4, 5], [6, 7, 8], [9]]>

tf.RaggedTensor の shape は未知の次元を含みます :

print(ragged_tensor.shape)
(4, None)

 

文字列 tensor

tf.string は dtype です、これはつまりデータを tensor の文字列 (可変長バイト配列) として表すことができるということです。

文字列はアトミックで Python 文字列がそうであるような方法でインデックスできません。文字列の長さは tensor の次元の一つではありません。それらを操作するための関数については tf.strings を見てください。

ここにスカラー文字列 tesor があります :

# Tensors can be strings, too here is a scalar string.
scalar_string_tensor = tf.constant("Gray wolf")
print(scalar_string_tensor)
tf.Tensor(b'Gray wolf', shape=(), dtype=string)

そして文字列のベクトル :

文字列のベクトル, shape: [3,]



# If you have three string tensors of different lengths, this is OK.
tensor_of_strings = tf.constant(["Gray wolf",
                                 "Quick brown fox",
                                 "Lazy dog"])
# Note that the shape is (3,). The string length is not included.
print(tensor_of_strings)
tf.Tensor([b'Gray wolf' b'Quick brown fox' b'Lazy dog'], shape=(3,), dtype=string)

上のプリントアウトで b プレフィックスは tf.string dtype がユニコード文字列ではなく、バイト文字列であることを示しています。TensorFlow でユニコード・テキストで作業することについてのより多くは Unicode チュートリアル を見てください。

ユニコード文字を渡す場合にはそれらは utf-8 エンコードされます。

tf.constant("🥳👍")
<tf.Tensor: shape=(), dtype=string, numpy=b'\xf0\x9f\xa5\xb3\xf0\x9f\x91\x8d'>

文字列を伴う幾つかの基本的な関数は tf.strings で見つけることができて、tf.strings.split を含みます。

# You can use split to split a string into a set of tensors
print(tf.strings.split(scalar_string_tensor, sep=" "))
tf.Tensor([b'Gray' b'wolf'], shape=(2,), dtype=string)
# ...but it turns into a `RaggedTensor` if you split up a tensor of strings,
# as each string might be split into a different number of parts.
print(tf.strings.split(tensor_of_strings))
<tf.RaggedTensor [[b'Gray', b'wolf'], [b'Quick', b'brown', b'fox'], [b'Lazy', b'dog']]>

Three strings split, shape: [3, None]

そして tf.string.to_number:

text = tf.constant("1 10 100")
print(tf.strings.to_number(tf.strings.split(text, " ")))
tf.Tensor([  1.  10. 100.], shape=(3,), dtype=float32)

文字列 tensor を数字に変えるために tf.cast を利用することっはできませんが、それをバイトに変換してから、数字に変換することはできます。

byte_strings = tf.strings.bytes_split(tf.constant("Duck"))
byte_ints = tf.io.decode_raw(tf.constant("Duck"), tf.uint8)
print("Byte strings:", byte_strings)
print("Bytes:", byte_ints)
Byte strings: tf.Tensor([b'D' b'u' b'c' b'k'], shape=(4,), dtype=string)
Bytes: tf.Tensor([ 68 117  99 107], shape=(4,), dtype=uint8)
# Or split it up as unicode and then decode it
unicode_bytes = tf.constant("アヒル 🦆")
unicode_char_bytes = tf.strings.unicode_split(unicode_bytes, "UTF-8")
unicode_values = tf.strings.unicode_decode(unicode_bytes, "UTF-8")

print("\nUnicode bytes:", unicode_bytes)
print("\nUnicode chars:", unicode_char_bytes)
print("\nUnicode values:", unicode_values)
Unicode bytes: tf.Tensor(b'\xe3\x82\xa2\xe3\x83\x92\xe3\x83\xab \xf0\x9f\xa6\x86', shape=(), dtype=string)

Unicode chars: tf.Tensor([b'\xe3\x82\xa2' b'\xe3\x83\x92' b'\xe3\x83\xab' b' ' b'\xf0\x9f\xa6\x86'], shape=(5,), dtype=string)

Unicode values: tf.Tensor([ 12450  12498  12523     32 129414], shape=(5,), dtype=int32)

tf.string dtype は TensorFlow の総ての raw バイトデータのために利用されます。tf.io モジュールは画像のデコードと csv の解析を含む、データをバイトに (and vice versa) 変換するための関数を含みます。

 

スパース tensor

時に、非常に広い埋め込み空間のように、貴方のデータはスパースです。TensorFlow はスパースデータを効率的にストアするために tf.sparse.SparseTensor と関連演算をサポートします。

A tf.SparseTensor, shape: [3, 4]

# Sparse tensors store values by index in a memory-efficient manner
sparse_tensor = tf.sparse.SparseTensor(indices=[[0, 0], [1, 2]],
                                       values=[1, 2],
                                       dense_shape=[3, 4])
print(sparse_tensor, "\n")

# You can convert sparse tensors to dense
print(tf.sparse.to_dense(sparse_tensor))
SparseTensor(indices=tf.Tensor(
[[0 0]
 [1 2]], shape=(2, 2), dtype=int64), values=tf.Tensor([1 2], shape=(2,), dtype=int32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64)) 

tf.Tensor(
[[1 0 0 0]
 [0 0 2 0]
 [0 0 0 0]], shape=(3, 4), dtype=int32)
 

以上



クラスキャット

最近の投稿

  • LangGraph 0.5 on Colab : Get started : カスタム・ワークフローの構築
  • LangGraph 0.5 on Colab : Get started : クイックスタート
  • LangGraph on Colab : SQL エージェントの構築
  • LangGraph on Colab : マルチエージェント・スーパーバイザー
  • LangGraph on Colab : エージェント型 RAG

タグ

AutoGen (13) ClassCat Press Release (20) ClassCat TF/ONNX Hub (11) DGL 0.5 (14) Eager Execution (7) Edward (17) FLUX.1 (16) Gemini (20) HuggingFace Transformers 4.5 (10) HuggingFace Transformers 4.6 (7) HuggingFace Transformers 4.29 (9) Keras 2 Examples (98) Keras 2 Guide (16) Keras 3 (10) Keras Release Note (17) Kubeflow 1.0 (10) LangChain (45) LangGraph (24) MediaPipe 0.8 (11) Model Context Protocol (16) NNI 1.5 (16) OpenAI Agents SDK (8) OpenAI Cookbook (13) OpenAI platform (10) OpenAI platform 1.x (10) OpenAI ヘルプ (8) TensorFlow 2.0 Advanced Tutorials (33) TensorFlow 2.0 Advanced Tutorials (Alpha) (15) TensorFlow 2.0 Advanced Tutorials (Beta) (16) TensorFlow 2.0 Guide (10) TensorFlow 2.0 Guide (Alpha) (16) TensorFlow 2.0 Guide (Beta) (9) TensorFlow 2.0 Release Note (12) TensorFlow 2.0 Tutorials (20) TensorFlow 2.0 Tutorials (Alpha) (14) TensorFlow 2.0 Tutorials (Beta) (12) TensorFlow 2.4 Guide (24) TensorFlow Deploy (8) TensorFlow Get Started (7) TensorFlow Graphics (7) TensorFlow Probability (9) TensorFlow Programmer's Guide (22) TensorFlow Release Note (18) TensorFlow Tutorials (33) TF-Agents 0.4 (11)
2020年12月
月 火 水 木 金 土 日
 123456
78910111213
14151617181920
21222324252627
28293031  
« 11月   1月 »
© 2025 ClasCat® AI Research | Powered by Minimalist Blog WordPress Theme