質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

3051閲覧

tf.keras.models.Model使用時のエラー: ValueError: The two structures don't have the same nested structure

Anonymous2020

総合スコア7

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/06/01 02:26

編集2021/06/01 03:31

前提・実現したいこと

tensorflow/kerasでLayerの自作に取り組んでいる者です

バッチ数x高さx幅xチャンネル数で構成される入力に対して、サイズを一回り縮小かつ1のみで
構成されたテンソルを返すlayerを作成しているのですがtf.keras.models.ModelにLayerを
組み込んだ際に

ValueError: The two structures don't have the same nested structure.

とエラーが出てきてしまいます。
おそらく、Layer内部のtf.while_loopの設定が間違っていると思うのですが、アドバイスいただけたら幸いです

よろしくお願いいたします。

該当のソースコード

python

1import numpy as np 2import tensorflow as tf 3from tensorflow.random import set_seed, uniform 4from tensorflow.keras.layers import Layer, MaxPool2D, Input 5 6set_seed(10) 7 8#---- サイズを一回り縮小した、1のみで構成されたテンソルを返すlayerを作成 9class maxpool_indices(Layer): 10 def __init__(self, pool_size=(2, 2), **kwargs): 11 super().__init__() 12 self.pool_size = pool_size 13 14 def call(self, inputs, *args, **kwargs): 15 16 #----inputの形からoutputの形を計算 17 kmax = tf.shape(inputs)[0] 18 imax = tf.shape(inputs)[1]-self.pool_size[0]+1 19 jmax = tf.shape(inputs)[2]-self.pool_size[1]+1 20 lmax = tf.shape(inputs)[3] 21 22 kijl_max = kmax*imax*jmax*lmax 23 24 #----繰り返し計算で1を積み上げていく -> [1,1,......,1] 25 def body(kijl, max_indices): 26 27 max_indices_new = tf.constant([1]) 28 max_indices = tf.cond(kijl == 0, 29 lambda: max_indices_new, 30 lambda: tf.concat([max_indices, max_indices_new], axis=-1)) 31 return tf.add(kijl,1), max_indices 32 33 def cond(kijl, max_indices): 34 return tf.less(kijl, kijl_max) 35 36 37 tmp, max_indices = tf.while_loop(cond, 38 body, 39 (tf.constant(0, name='init'), tf.constant([-1], name='dummy_const')), 40 shape_invariants=tf.TensorShape([1, None])) 41 #----[1,1,......,1]を バッチ数x高さx幅xチャンネル数 に整形 42 return tf.reshape(max_indices, (kmax, imax, jmax, lmax)) 43 44#----動作確認 45batch = 1 46width = 4 47height = 4 48channel = 1 49input = tf.random.uniform(shape=[batch, height, width, channel], 50 minval=0, maxval=10, 51 dtype=tf.dtypes.int32 ) 52 53x = maxpool_indices()(input) 54display(x) 55''' 56上記は動作確認済み(下記出力) 57<tf.Tensor: shape=(1, 3, 3, 1), dtype=int32, numpy= 58array([[[[1], 59 [1], 60 [1]], 61 62 [[1], 63 [1], 64 [1]], 65 66 [[1], 67 [1], 68 [1]]]], dtype=int32)> 69''' 70 71def custom_model(): 72 inputs = Input(shape=(height, width, channel)) 73 x = maxpool_indices()(inputs) ##########ここでエラーが検出される######### 74 return tf.keras.models.Model(inputs,x) 75 76cm = custom_model() 77 78

発生している問題・エラーメッセージ

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-aa34b0004977> in <module>() 58 return tf.keras.models.Model(inputs,x) 59 ---> 60 cm = custom_model() 5 frames <ipython-input-5-aa34b0004977> in custom_model() 55 def custom_model(): 56 inputs = Input(shape=(height, width, channel)) ---> 57 x = maxpool_indices()(inputs) 58 return tf.keras.models.Model(inputs,x) 59 /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, *args, **kwargs) 968 if _in_functional_construction_mode(self, inputs, args, kwargs, input_list): 969 return self._functional_construction_call(inputs, args, kwargs, --> 970 input_list) 971 972 # Maintains info about the `Layer.call` stack. /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py in _functional_construction_call(self, inputs, args, kwargs, input_list) 1106 # Check input assumptions set after layer building, e.g. input shape. 1107 outputs = self._keras_tensor_symbolic_call( -> 1108 inputs, input_masks, args, kwargs) 1109 1110 if outputs is None: /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py in _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs) 838 return nest.map_structure(keras_tensor.KerasTensor, output_signature) 839 else: --> 840 return self._infer_output_signature(inputs, args, kwargs, input_masks) 841 842 def _infer_output_signature(self, inputs, args, kwargs, input_masks): /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py in _infer_output_signature(self, inputs, args, kwargs, input_masks) 878 self._maybe_build(inputs) 879 inputs = self._maybe_cast_inputs(inputs) --> 880 outputs = call_fn(inputs, *args, **kwargs) 881 882 self._handle_activity_regularization(inputs, outputs) /usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs) 693 except Exception as e: # pylint:disable=broad-except 694 if hasattr(e, 'ag_error_metadata'): --> 695 raise e.ag_error_metadata.to_exception(e) 696 else: 697 raise ValueError: in user code: <ipython-input-5-aa34b0004977>:45 call * tmp, max_indices = tf.while_loop(cond, /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/deprecation.py:602 new_func ** return func(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/control_flow_ops.py:2541 while_loop_v2 return_same_structure=True) /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/control_flow_ops.py:2738 while_loop back_prop=back_prop) /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/while_v2.py:84 while_loop expand_composites=False) /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/nest.py:533 assert_same_structure % (str(e), str1, str2)) ValueError: The two structures don't have the same nested structure. First structure: type=tuple str=(<tf.Tensor 'maxpool_indices_6/init:0' shape=() dtype=int32>, <tf.Tensor 'maxpool_indices_6/dummy_const:0' shape=(1,) dtype=int32>) Second structure: type=TensorShape str=(1, None) More specifically: Substructure "type=tuple str=(<tf.Tensor 'maxpool_indices_6/init:0' shape=() dtype=int32>, <tf.Tensor 'maxpool_indices_6/dummy_const:0' shape=(1,) dtype=int32>)" is a sequence, while substructure "type=TensorShape str=(1, None)" is not Entire first structure: (., .) Entire second structure: .

試したこと

ここに問題に対して試したことを記載してください。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

下記への変更で解決しました
お手数おかけしました。

python

1shape_invariants=(tf.TensorShape(1), tf.TensorShape([None])

投稿2021/06/02 00:49

Anonymous2020

総合スコア7

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問