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

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

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

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

Google Colaboratory

Google Colaboratoryとは、無償のJupyterノートブック環境。教育や研究機関の機械学習の普及のためのGoogleの研究プロジェクトです。PythonやNumpyといった機械学習で要する大方の環境がすでに構築されており、コードの記述・実行、解析の保存・共有などが可能です。

Python

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

Q&A

解決済

1回答

1382閲覧

ValueError: Shapes (128, 128, 1) and (128, 128, 3) are incompatible

tkrd

総合スコア5

Keras

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

Google Colaboratory

Google Colaboratoryとは、無償のJupyterノートブック環境。教育や研究機関の機械学習の普及のためのGoogleの研究プロジェクトです。PythonやNumpyといった機械学習で要する大方の環境がすでに構築されており、コードの記述・実行、解析の保存・共有などが可能です。

Python

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

0グッド

0クリップ

投稿2021/08/29 14:29

閲覧いただきありがとうございます。畳み込み層を用いたオートエンコーダでタイトルのエラーが解決できなかったため質問いたしました。

扱うデータがグレースケールであるため、x_trainとx_validをreshapeで変換しました。x_trainのshapeは(128,128,1)と変換できているのに対し、x_validが(128,128,3)でありshapeが違うのが問題であるとは思うのですが、解決できませんでした。

ちなみに入力しているデータは128*128のデータが146枚となっています。

初心者の質問で申し訳ありませんがよろしくお願い致します。

エラーコード

ValueError Traceback (most recent call last) <ipython-input-6-39c46d683b62> in <module>() 62 batch_size=32, 63 shuffle=False, ---> 64 validation_data=(x_valid, x_valid)) 65 66 encoded_img = encoder.predict(x_train) 9 frames /usr/local/lib/python3.7/dist-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing) 1182 _r=1): 1183 callbacks.on_train_batch_begin(step) -> 1184 tmp_logs = self.train_function(iterator) 1185 if data_handler.should_sync: 1186 context.async_wait() /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds) 883 884 with OptionalXlaContext(self._jit_compile): --> 885 result = self._call(*args, **kwds) 886 887 new_tracing_count = self.experimental_get_tracing_count() /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds) 931 # This is the first call of __call__, so we have to initialize. 932 initializers = [] --> 933 self._initialize(args, kwds, add_initializers_to=initializers) 934 finally: 935 # At this point we know that the initialization is complete (or less /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to) 758 self._concrete_stateful_fn = ( 759 self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access --> 760 *args, **kwds)) 761 762 def invalid_creator_scope(*unused_args, **unused_kwds): /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs) 3064 args, kwargs = None, None 3065 with self._lock: -> 3066 graph_function, _ = self._maybe_define_function(args, kwargs) 3067 return graph_function 3068 /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs) 3461 3462 self._function_cache.missed.add(call_context_key) -> 3463 graph_function = self._create_graph_function(args, kwargs) 3464 self._function_cache.primary[cache_key] = graph_function 3465 /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 3306 arg_names=arg_names, 3307 override_flat_arg_shapes=override_flat_arg_shapes, -> 3308 capture_by_value=self._capture_by_value), 3309 self._function_attributes, 3310 function_spec=self.function_spec, /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes, acd_record_initial_resource_uses) 1005 _, original_func = tf_decorator.unwrap(python_func) 1006 -> 1007 func_outputs = python_func(*func_args, **func_kwargs) 1008 1009 # invariant: `func_outputs` contains only Tensors, CompositeTensors, /usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds) 666 # the function a weak reference to itself to avoid a reference cycle. 667 with OptionalXlaContext(compile_with_xla): --> 668 out = weak_wrapped_fn().__wrapped__(*args, **kwds) 669 return out 670 /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 992 except Exception as e: # pylint:disable=broad-except 993 if hasattr(e, "ag_error_metadata"): --> 994 raise e.ag_error_metadata.to_exception(e) 995 else: 996 raise ValueError: in user code: /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:853 train_function * return step_function(self, iterator) <ipython-input-6-39c46d683b62>:38 ssim_loss * return 1-tf.reduce_mean(tf.image.ssim(y_true, y_pred, /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper ** return target(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py:4304 ssim _, _, checks = _verify_compatible_image_shapes(img1, img2) /usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/image_ops_impl.py:3994 _verify_compatible_image_shapes shape1[-3:].assert_is_compatible_with(shape2[-3:]) /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_shape.py:1161 assert_is_compatible_with raise ValueError("Shapes %s and %s are incompatible" % (self, other)) ValueError: Shapes (128, 128, 1) and (128, 128, 3) are incompatible

ソースコード

python

1from keras.layers import Input, Conv2D, BatchNormalization, Activation, MaxPooling2D, UpSampling2D, Reshape 2from keras.models import Model 3from keras.preprocessing.image import load_img, save_img, img_to_array, array_to_img 4import os 5import glob 6from PIL import Image 7import numpy as np 8from sklearn.model_selection import train_test_split 9import matplotlib.pyplot as plt 10from google.colab import drive 11import sunpy.map 12 13drive.mount('/content/drive', force_remount=True) 14 15input_data = np.load('drive/My Drive/study/temp_201005_AR8_resize_128128.npy') 16t = np.zeros(input_data.shape[0],dtype='int32') 17 18input_img = Input(shape=(128, 128,)) 19hidden = Reshape((128, 128, 1), input_shape = (128, 128))(input_img) 20x = Conv2D(64, (3, 3), padding='same')(hidden) 21x = BatchNormalization()(x) 22x = Activation('relu')(x) 23x = MaxPooling2D((2, 2), padding='same')(x) 24x = Conv2D(32, (3, 3), padding='same')(x) 25x = BatchNormalization()(x) 26x = Activation('relu')(x) 27x = MaxPooling2D((2, 2), padding='same')(x) 28x = Conv2D(16, (3, 3), padding='same')(x) 29x = BatchNormalization()(x) 30x = Activation('relu')(x) 31encoded = MaxPooling2D((2, 2), padding='same')(x) 32 33x = Conv2D(16, (3, 3), padding='same')(encoded) 34x = BatchNormalization()(x) 35x = Activation('relu')(x) 36x = UpSampling2D((2, 2))(x) 37x = Conv2D(32, (3, 3), padding='same')(x) 38x = BatchNormalization()(x) 39x = Activation('relu')(x) 40x = UpSampling2D((2, 2))(x) 41x = Conv2D(64, (3, 3), padding='same')(x) 42x = BatchNormalization()(x) 43x = Activation('relu')(x) 44x = UpSampling2D((2, 2))(x) 45x = Conv2D(3, (3, 3), padding='same')(x) 46x = BatchNormalization()(x) 47decoded = Activation('sigmoid')(x) 48 49autoencoder = Model(input_img, decoded) 50 51from keras import optimizers 52import tensorflow as tf 53 54def ssim_loss(y_true, y_pred): 55 return 1-tf.reduce_mean(tf.image.ssim(y_true, y_pred, 56 max_val = 1.0,filter_size=11, 57 filter_sigma=1.5, k1=0.01, k2=0.03 )) 58 59adam = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False) 60autoencoder.compile(optimizer=adam, loss=ssim_loss) 61 62x_train_valid, x_test, t_train_valid, t_test = train_test_split(input_data, t, test_size=0.1, shuffle=42) 63x_train, x_valid, t_train, t_valid = train_test_split(x_train_valid, t_train_valid, test_size=0.1) 64x_train = (x_train.astype('float32')+2000)/4000. 65x_valid = (x_valid.astype('float32')+2000)/4000. 66x_test = (x_test.astype('float32')+2000)/4000. 67 68x_train = x_train.reshape((-1, 128, 128, 1)) 69x_valid = x_valid.reshape((-1, 128, 128, 1)) 70#x_test = x_test.reshape((-1, 128, 128, 1)) 71 72print(x_train.shape) 73print(x_valid.shape) 74print(x_test.shape) 75 76# run autoencoder 77hist = autoencoder.fit(x_train, x_train, 78 epochs=20, 79 batch_size=32, 80 shuffle=False, 81 validation_data=(x_valid, x_valid)) ##ここでエラーが出る 82 83encoded_img = encoder.predict(x_train) 84decoded_img = decoder.predict(encoded_img)

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

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

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

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

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

jbpb0

2021/08/30 06:51

> 入力しているデータは128*128のデータが146枚 input_data = np.load(... のすぐ次に print(input_data.shape) を追加して実行したら、その結果は (146, 128, 128) と表示されるのでしょうか?
jbpb0

2021/08/30 07:27 編集

autoencoder = Model(input_img, decoded) のすぐ次に print(autoencoder.summary()) を追加して実行したら、その結果の一番下の近くに 「activation_7 (Activation) (None, 128, 128, 3) 0 」 と表示されますけど、それの「(None, 128, 128, 3)」が、画像に合わせて「(None, 128, 128, 1)」とならないとダメなのではないですかね x = Conv2D(3, (3, 3), padding='same')(x) x = BatchNormalization()(x) decoded = Activation('sigmoid')(x) の「Conv2D(3,」を「Conv2D(1,」と変えたら、「(None, 128, 128, 1)」となると思います 質問者さんの意図と合ってるかは分かりませんが
tkrd

2021/08/30 07:57

はい。一件目の事柄についてその通りで、reshape後はx_trainであればデータを分割しているために(117, 128, 128, 1)になります。
tkrd

2021/08/30 08:04

jbpb0さんのおっしゃる通りコードを変更したところ同箇所のエラーは無事解決いたしました。ありがとうございます。。
guest

回答1

0

自己解決

x = Conv2D(3, (3, 3), padding='same')(x)
x = BatchNormalization()(x)
decoded = Activation('sigmoid')(x)
の「Conv2D(3,」を「Conv2D(1,」と変えたら、解決しました。

投稿2021/08/30 13:13

tkrd

総合スコア5

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問