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

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

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

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

Python 3.x

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

Q&A

0回答

731閲覧

siamese networkのペア付けをミニバッチごとに行いたい

xeno

総合スコア16

Keras

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

Python 3.x

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

0グッド

0クリップ

投稿2022/01/04 13:30

行いたいこと:siamese networkのペア付けをミニバッチごとに行えるように変更したいと考えています。
現状:そこで、ペア付けの関数(make_pairs)をfit_generatorで呼び出すようにしたのですがエラーにより実装できていません。
教えて頂きたいこと:ペア付けをミニバッチごとに行って学習できるようにする部分まで教えて頂きたいです。

import random import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import matplotlib.pyplot as plt from time import time import os from sklearn.manifold import TSNE t_start = time() # 開始時間 """ ## Hyperparameters """ save_dir ='/home/practice/siamese_model/' epochs = 100 batch_size = 12 margin = 1 # Margin for constrastive loss. def make_pairs(batch_size): (x_train_val, y_train_val), (x_test, y_test) = keras.datasets.mnist.load_data() x_train_val = x_train_val.astype("float32") x_test = x_test.astype("float32") # Keep 50% of train_val in validation set x_train, x_val = x_train_val[:30000], x_train_val[30000:] y_train, y_val = y_train_val[:30000], y_train_val[30000:] x = x_train y = y_train num_classes = max(y) + 1 digit_indices = [np.where(y == i)[0] for i in range(num_classes)] pairs = [] labels = [] count = 0 for idx1 in range(len(x)): count += 1 # add a matching example x1 = x[idx1] label1 = y[idx1] idx2 = random.choice(digit_indices[label1]) x2 = x[idx2] pairs += [[x1, x2]] labels += [1] # add a non-matching example label2 = random.randint(0, num_classes - 1) while label2 == label1: label2 = random.randint(0, num_classes - 1) idx2 = random.choice(digit_indices[label2]) x2 = x[idx2] pairs += [[x1, x2]] labels += [0] print('All pair is ',count) pairs = np.array(pairs) x_train_1 = pairs[:, 0] # x_train_1.shape is (60000, 28, 28) x_train_1=x_train_1.reshape(x_train_1.shape[0],x_train_1.shape[1],x_train_1.shape[2],1) x_train_2 = pairs[:, 1] x_train_2=x_train_2.reshape(x_train_2.shape[0],x_train_2.shape[1],x_train_2.shape[2],1) yield [x_train_1,x_train_2], np.array(labels).astype("float32") # Provided two tensors t1 and t2 # Euclidean distance = sqrt(sum(square(t1-t2))) def euclidean_distance(vects): x, y = vects sum_square = tf.math.reduce_sum(tf.math.square(x - y), axis=1, keepdims=True) a = tf.math.sqrt(tf.math.maximum(sum_square, tf.keras.backend.epsilon())) print(a) return a input = layers.Input((28,28,1)) x = tf.keras.layers.BatchNormalization()(input) x = layers.Conv2D(4, (5, 5), activation="tanh")(x) x = layers.AveragePooling2D(pool_size=(2, 2))(x) x = layers.Conv2D(16, (5, 5), activation="tanh")(x) x = layers.AveragePooling2D(pool_size=(2, 2))(x) x = layers.Flatten()(x) x = tf.keras.layers.BatchNormalization()(x) x = layers.Dense(10, activation="tanh")(x) embedding_network = keras.Model(input, x) input_1 = layers.Input((28,28,1)) input_2 = layers.Input((28,28,1)) # As mentioned above, Siamese Network share weights between # tower networks (sister networks). To allow this, we will use # same embedding network for both tower networks. tower_1 = embedding_network(input_1) tower_2 = embedding_network(input_2) merge_layer = layers.Lambda(euclidean_distance)([tower_1, tower_2]) normal_layer = tf.keras.layers.BatchNormalization()(merge_layer) output_layer = layers.Dense(1, activation="sigmoid")(normal_layer) siamese = keras.Model(inputs=[input_1, input_2], outputs=output_layer) """ ## Define the constrastive Loss """ def loss(margin=1): # Contrastive loss = mean( (1-true_value) * square(prediction) + # true_value * square( max(margin-prediction, 0) )) def contrastive_loss(y_true, y_pred): print('y_pred',y_pred) print('y_true',y_true) square_pred = tf.math.square(y_pred) margin_square = tf.math.square(tf.math.maximum(margin - (y_pred), 0)) return tf.math.reduce_mean( (1 - y_true) * square_pred + (y_true) * margin_square ) return contrastive_loss siamese.compile(loss=loss(margin=margin), optimizer="RMSprop", metrics=["accuracy"]) tf.keras.utils.plot_model(siamese, to_file = 'model2.png', show_shapes = True, show_layer_names = True) siamese.summary() history = siamese.fit_generator( make_pairs(batch_size=batch_size), steps_per_epoch = 2000, epochs=epochs ) siamese.save('/home/practice/siamese_model/model.hdf5') t_end = time() #終了時間 t_elapsed = t_end - t_start print("処理時間は{0}".format(t_elapsed))

エラー

All pair is 30000 Epoch 1/100 WARNING:tensorflow:From /home/.local/lib/python3.6/site-packages/tensorflow/python/ops/math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where 2022-01-04 22:29:48.600988: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcublas.so.10.0 2022-01-04 22:29:48.902468: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudnn.so.7 1/2000 [..............................] - ETA: 2:32:27 - loss: 0.2255 - acc: 0.6391WARNING:tensorflow:Your dataset iterator ran out of data; interrupting training. Make sure that your iterator can generate at least `steps_per_epoch * epochs` batches (in this case, 200000 batches). You may need touse the repeat() function when building your dataset.

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問