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 Graphics : Tutorials : 物体ポーズ推定 / 整列

Posted on 05/25/2019 by Sales Information

TensorFlow Graphics : Beginner Tutorials : 物体ポーズ推定 / 整列 (翻訳/解説)

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

* 本ページは、TensorFlow Graphics の github レポジトリの次のページを翻訳した上で適宜、補足説明したものです:

  • https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/notebooks/6dof_alignment.ipynb

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

 

TensorFlow Graphics : Beginner Tutorials : 物体ポーズ推定 / 整列

物体のポーズを正確に推定することは多くの業種 (= industries) で基本的です。例えば拡張現実と仮想現実において、これらのオブジェクトと相互作用することによりそれはユーザに幾つかの変数の状態を変更することを可能にします (e.g. ユーザのデスクの上のマグにより制御される容量)。

このノートブックは既知の 3D 物体の回転と移動を推定するために TensorFlow Graphics をどのように使用するかを示します。

この能力は 2 つの異なるデモにより示されます :

  1. 機械学習デモ、これは与えられた物体の参照ポーズに関する回転と移動を正確に見積もることができる単純なニューラルネットワークをどのように訓練するかを示します。
  2. 数学的最適化デモ、これはこの問題への異なるアプローチを取ります ; 機械学習は使用しません。

 

セットアップ & Imports

このノートブックに含まれるデモを実行するために必要な総てを import しましょう。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

from tensorflow_graphics.geometry.transformation import quaternion
from tensorflow_graphics.math import vector
from tensorflow_graphics.notebooks import threejs_visualization
from tensorflow_graphics.notebooks.resources import tfg_simplified_logo

tf.enable_eager_execution()

# Loads the Tensorflow Graphics simplified logo.
vertices = tfg_simplified_logo.mesh['vertices'].astype(np.float32)
faces = tfg_simplified_logo.mesh['faces']
num_vertices = vertices.shape[0]

 

1. 機械学習

モデル定義

既知のメッシュの総ての頂点の 3D 位置が与えられたとき、参照ポーズに関するこのメッシュの (クォータニオン (4 次元ベクトル) によりパラメータ化された) 回転と移動 (3 次元ベクトル) を予測する能力があるネットワークを望みます。今、タスクのための非常に単純な 3-層完全結合ネットワークと損失を作成しましょう。このモデルは非常に単純で明らかに最善ではないことに注意してください、それはこのノートブックのためには範囲外です。

# モデルを構築する。
model = keras.Sequential()
model.add(layers.Flatten(input_shape=(num_vertices, 3)))
model.add(layers.Dense(64, activation=tf.nn.tanh))
model.add(layers.Dense(64, activation=tf.nn.relu))
model.add(layers.Dense(7))


def pose_estimation_loss(y_true, y_pred):
  """訓練のために使用されるポーズ推定損失。

  This loss measures the average of squared distance between some vertices
  of the mesh in 'rest pose' and the transformed mesh to which the predicted
  inverse pose is applied. Comparing this loss with a regular L2 loss on the
  quaternion and translation values is left as exercise to the interested
  reader.

  Args:
    y_true: The ground-truth value.
    y_pred: The prediction we want to evaluate the loss for.

  Returns:
    A scalar value containing the loss described in the description above.
  """
  # y_true.shape : (batch, 7)
  y_true_q, y_true_t = tf.split(y_true, (4, 3), axis=-1)
  # y_pred.shape : (batch, 7)
  y_pred_q, y_pred_t = tf.split(y_pred, (4, 3), axis=-1)

  # vertices.shape: (num_vertices, 3)
  # corners.shape:(num_vertices, 1, 3)
  corners = tf.expand_dims(vertices, axis=1)

  # transformed_corners.shape: (num_vertices, batch, 3)
  # q and t shapes get pre-pre-padded with 1's following standard broadcast rules.
  transformed_corners = quaternion.rotate(corners, y_pred_q) + y_pred_t

  # recovered_corners.shape: (num_vertices, batch, 3)
  recovered_corners = quaternion.rotate(transformed_corners - y_true_t,
                                        quaternion.inverse(y_true_q))

  # vertex_error.shape: (num_vertices, batch)
  vertex_error = tf.reduce_sum((recovered_corners - corners)**2, axis=-1)

  return tf.reduce_mean(vertex_error)


optimizer = keras.optimizers.Adam()
model.compile(loss=pose_estimation_loss, optimizer=optimizer)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, 114)               0         
_________________________________________________________________
dense (Dense)                (None, 64)                7360      
_________________________________________________________________
dense_1 (Dense)              (None, 64)                4160      
_________________________________________________________________
dense_2 (Dense)              (None, 7)                 455       
=================================================================
Total params: 11,975
Trainable params: 11,975
Non-trainable params: 0
_________________________________________________________________

 

データ生成

モデルを定義した今、それを訓練するためのデータが必要です。訓練セットの各サンプルについて、ランダムな 3D 回転と 3D 移動がサンプリングされて物体の頂点に適用されます。各訓練サンプルは総ての変換された頂点と (サンプルに適用された) 回転と移動を戻すことを可能にする反対の回転と移動から成ります。

def generate_training_data(num_samples):
  # random_angles.shape: (num_samples, 3)
  random_angles = np.random.uniform(-np.pi, np.pi,
                                    (num_samples, 3)).astype(np.float32)

  # random_quaternion.shape: (num_samples, 4)
  random_quaternion = quaternion.from_euler(random_angles)

  # random_translation.shape: (num_samples, 3)
  random_translation = np.random.uniform(-2.0, 2.0,
                                         (num_samples, 3)).astype(np.float32)

  # data.shape : (num_samples, num_vertices, 3)
  data = quaternion.rotate(vertices[tf.newaxis, :, :],
                           random_quaternion[:, tf.newaxis, :]
                          ) + random_translation[:, tf.newaxis, :]

  # target.shape : (num_samples, 4+3)
  target = tf.concat((random_quaternion, random_translation), axis=-1)

  return np.array(data), np.array(target)
num_samples = 10000

data, target = generate_training_data(num_samples)

print(data.shape)   # (num_samples, num_vertices, 3): the vertices
print(target.shape)  # (num_samples, 4+3): the quaternion and translation
(10000, 38, 3)
(10000, 7)

 

訓練

この時点で、ニューラルネットワークの訓練を開始するために総てが適切です!

# Callback allowing to display the progression of the training task.
class ProgressTracker(keras.callbacks.Callback):

  def __init__(self, num_epochs, step=5):
    self.num_epochs = num_epochs
    self.current_epoch = 0.
    self.step = step
    self.last_percentage_report = 0

  def on_epoch_end(self, batch, logs={}):
    self.current_epoch += 1.
    training_percentage = int(self.current_epoch * 100.0 / self.num_epochs)
    if training_percentage - self.last_percentage_report >= self.step:
      print('Training ' + str(
          training_percentage) + '% complete. Training loss: ' + str(
              logs.get('loss')) + ' | Validation loss: ' + str(
                  logs.get('val_loss')))
      self.last_percentage_report = training_percentage
reduce_lr_callback = keras.callbacks.ReduceLROnPlateau(
    monitor='val_loss',
    factor=0.5,
    patience=10,
    verbose=0,
    mode='auto',
    min_delta=0.0001,
    cooldown=0,
    min_lr=0)
# Everything is now in place to train.
EPOCHS = 100
pt = ProgressTracker(EPOCHS)
history = model.fit(
    data,
    target,
    epochs=EPOCHS,
    validation_split=0.2,
    verbose=0,
    batch_size=32,
    callbacks=[reduce_lr_callback, pt])

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.ylim([0, 1])
plt.legend(['loss', 'val loss'], loc='upper left')
plt.xlabel('Train epoch')
_ = plt.ylabel('Error [mean square distance]')
Training 5% complete. Training loss: 1.009950121998787 | Validation loss: 0.9137270336151123
Training 10% complete. Training loss: 0.5268501298427581 | Validation loss: 0.5240717251300812
Training 15% complete. Training loss: 0.3752533705532551 | Validation loss: 0.37031882667541505
Training 20% complete. Training loss: 0.29893275210261344 | Validation loss: 0.29115591061115265
Training 25% complete. Training loss: 0.24757031705975532 | Validation loss: 0.23939514791965485
Training 30% complete. Training loss: 0.22420285016298294 | Validation loss: 0.21258240276575088
Training 35% complete. Training loss: 0.19799123887717723 | Validation loss: 0.1807250078320503
Training 40% complete. Training loss: 0.17767862628400327 | Validation loss: 0.1784087748527527
Training 45% complete. Training loss: 0.17318876099586486 | Validation loss: 0.15155328786373137
Training 50% complete. Training loss: 0.15236466732621193 | Validation loss: 0.16674353015422821
Training 55% complete. Training loss: 0.13417977157235145 | Validation loss: 0.13277354818582535
Training 60% complete. Training loss: 0.15286476877331734 | Validation loss: 0.13142506104707719
Training 65% complete. Training loss: 0.13228631572425364 | Validation loss: 0.13619410294294357
Training 70% complete. Training loss: 0.1253597312271595 | Validation loss: 0.11984566831588746
Training 75% complete. Training loss: 0.08613634746521712 | Validation loss: 0.09534638980031014
Training 80% complete. Training loss: 0.07220880922675132 | Validation loss: 0.07457096055150032
Training 85% complete. Training loss: 0.07194197417795659 | Validation loss: 0.055152468413114546
Training 90% complete. Training loss: 0.06660718904435635 | Validation loss: 0.07816255846619606
Training 95% complete. Training loss: 0.07537854766100645 | Validation loss: 0.08529620145261288
Training 100% complete. Training loss: 0.04841766462475061 | Validation loss: 0.05356932772696018

 

テスティング

今ではネットワークは訓練されて利用する準備ができました!表示される結果は 2 つの画像から成ります。最初の画像は「静止ポーズ (= rest pose)」にある物体 (パステル・レモン色) と回転されて移動された物体 (パステル・ハニーデュー色) を含みます。これは 2 つの構成がどのように異なるかを観察することを効果的に可能にします。2 番目の画像はまた静止ポーズの物体を示しますが、今回は訓練されたニューラルネットワークにより予測された変換が回転されて移動されたバージョンに適用されます。望ましくは、2 つの物体が今では非常に類似したポーズであることです。

Note: 異なるテストケースをサンプリングするために複数回プレーを押してください。貴方は時々物体のスケーリングが無効であることに気付くでしょう。これはクォータニオンがスケールをエンコードできるという事実に由来します。単位ノルムのクォータニオンの使用は結果のスケールを変更しないという結果になるでしょう。ネットワーク・アーキテクチャか損失関数でこの制約を追加する実験を興味ある読者に委ねます。

クォータニオンと移動を適用するヘルパー関数から始めます :

# Defines the loss function to be optimized.
def transform_points(target_points, quaternion_variable, translation_variable):
  return quaternion.rotate(target_points,
                           quaternion_variable) + translation_variable

変換された形状のための threejs ビューアを定義します :

class Viewer(object):

  def __init__(self, my_vertices):
    my_vertices = np.asarray(my_vertices)
    context = threejs_visualization.build_context()
    light1 = context.THREE.PointLight.new_object(0x808080)
    light1.position.set(10., 10., 10.)
    light2 = context.THREE.AmbientLight.new_object(0x808080)
    lights = (light1, light2)

    material = context.THREE.MeshLambertMaterial.new_object({
        'color': 0xfffacd,
    })

    material_deformed = context.THREE.MeshLambertMaterial.new_object({
        'color': 0xf0fff0,
    })

    camera = threejs_visualization.build_perspective_camera(
        field_of_view=30, position=(10.0, 10.0, 10.0))

    mesh = {'vertices': vertices, 'faces': faces, 'material': material}
    transformed_mesh = {
        'vertices': my_vertices,
        'faces': faces,
        'material': material_deformed
    }
    geometries = threejs_visualization.triangular_mesh_renderer(
        [mesh, transformed_mesh],
        lights=lights,
        camera=camera,
        width=400,
        height=400)

    self.geometries = geometries

  def update(self, transformed_points):
    self.geometries[1].getAttribute('position').copyArray(
        transformed_points.numpy().ravel().tolist())
    self.geometries[1].getAttribute('position').needsUpdate = True

ランダム回転と移動を定義します :

def get_random_transform():
  # Forms a random translation
  with tf.name_scope('translation_variable'):
    random_translation = tf.Variable(
        np.random.uniform(-2.0, 2.0, (3,)), dtype=tf.float32)

  # Forms a random quaternion
  hi = np.pi
  lo = -hi
  random_angles = np.random.uniform(lo, hi, (3,)).astype(np.float32)
  with tf.name_scope('rotation_variable'):
    random_quaternion = tf.Variable(quaternion.from_euler(random_angles))

  return random_quaternion, random_translation

変換パラメータを予測するモデルを実行して、結果を可視化します :

random_quaternion, random_translation = get_random_transform()

initial_orientation = transform_points(vertices, random_quaternion,
                                       random_translation).numpy()
viewer = Viewer(initial_orientation)

predicted_transformation = model.predict(initial_orientation[tf.newaxis, :, :])

predicted_inverse_q = quaternion.inverse(predicted_transformation[0, 0:4])
predicted_inverse_t = -predicted_transformation[0, 4:]

predicted_aligned = quaternion.rotate(initial_orientation + predicted_inverse_t,
                                      predicted_inverse_q)

viewer = Viewer(predicted_aligned)

 
(訳注 : 幾つかの実行サンプルを以下に示します : )

 

2. 数学的最適化

ここでは問題は数学的最適化を使用して取り組まれます、これは物体ポーズ推定の問題にアプローチするためのもう一つの伝統的な方法です。「静止ポーズ」にある物体 (パステルレモン色) とその回転されて移動された対応物体 (パステルハニーデュー色) 間の対応が与えられたとき、問題は最小化問題として定式化できます。損失関数は例えば、変換された物体の回転と移動の現在の推定を使用して対応する点のユークリッド距離の総計として定義できます。そしてこの損失に関する回転と移動パラメータの導関数を計算して、収束まで勾配方向をフォローできます。次のセルはこの手続きを密接にフォローし、そして 2 つの物体を整列するために勾配効果を使用します。結果は良いですが、注目すべき点としてこの特定の問題を解くためにより効率的な方法があります。興味ある読者はより詳細について Kabsch アルゴリズムを参照してください。

Note: 異なるテストケースをサンプリングするために複数回プレーを押してください。

損失と勾配関数を定義します :

def loss(target_points, quaternion_variable, translation_variable):
  transformed_points = transform_points(target_points, quaternion_variable,
                                        translation_variable)
  error = (vertices - transformed_points) / num_vertices
  return vector.dot(error, error)


def gradient_loss(target_points, quaternion, translation):
  with tf.GradientTape() as tape:
    loss_value = loss(target_points, quaternion, translation)
  return tape.gradient(loss_value, [quaternion, translation])

optimizer を作成します。

learning_rate = 0.05
with tf.name_scope('optimization'):
  optimizer = tf.train.AdamOptimizer(learning_rate)

ランダム変換を初期化して、最適化を実行して結果をアニメーションにします。

random_quaternion, random_translation = get_random_transform()

transformed_points = transform_points(vertices, random_quaternion,
                                      random_translation)

viewer = Viewer(transformed_points)

nb_iterations = 100
for it in range(nb_iterations):
  gradients_loss = gradient_loss(vertices, random_quaternion,
                                 random_translation)
  optimizer.apply_gradients(
      zip(gradients_loss, (random_quaternion, random_translation)))
  transformed_points = transform_points(vertices, random_quaternion,
                                        random_translation)

  viewer.update(transformed_points)
  time.sleep(0.1)
 

以上






クラスキャット

最近の投稿

  • LangGraph on Colab : エージェント型 RAG
  • LangGraph : 例題 : エージェント型 RAG
  • LangGraph Platform : Get started : クイックスタート
  • LangGraph Platform : 概要
  • LangGraph : Prebuilt エージェント : ユーザインターフェイス

タグ

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 (22) 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)
2019年5月
月 火 水 木 金 土 日
 12345
6789101112
13141516171819
20212223242526
2728293031  
« 4月   6月 »
© 2025 ClasCat® AI Research | Powered by Minimalist Blog WordPress Theme