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

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

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

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

深層学習

深層学習は、多数のレイヤのニューラルネットワークによる機械学習手法。人工知能研究の一つでディープラーニングとも呼ばれています。コンピューター自体がデータの潜在的な特徴を汲み取り、効率的で的確な判断を実現することができます。

Python

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

Q&A

0回答

1271閲覧

kerasでの自作モデルで学習を始めることができない

siroto

総合スコア2

Keras

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

深層学習

深層学習は、多数のレイヤのニューラルネットワークによる機械学習手法。人工知能研究の一つでディープラーニングとも呼ばれています。コンピューター自体がデータの潜在的な特徴を汲み取り、効率的で的確な判断を実現することができます。

Python

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

0グッド

0クリップ

投稿2020/11/05 07:49

現在このようなモデルを作成しています.

python

1import os 2import glob 3from PIL import Image 4import numpy as np 5import keras 6# os.environ['CUDA_VISIBLE_DEVICES'] = '/job:localhost/replica:0/task:0/device:GPU:0' 7# keras modules 8from keras.preprocessing.image import load_img,img_to_array 9os.environ["KERAS_BACKEND"] = "tensorflow" 10kerasBKED = os.environ["KERAS_BACKEND"] 11from tensorflow.keras.models import load_model 12from tensorflow.keras.datasets import cifar10 13from tensorflow.keras.layers import Input, Dense, Conv2D, Reshape,MaxPooling2D, UpSampling2D, ZeroPadding2D,BatchNormalization, Activation,AveragePooling2D,Dropout,Flatten 14from tensorflow.keras.models import Model , Sequential 15from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint 16from tensorflow.keras.optimizers import Adam,SGD 17from tensorflow.keras import layers 18import tensorflow.keras.backend as K 19import tensorflow as tf 20from tqdm import tnrange 21import matplotlib.pyplot as plt 22import matplotlib 23import cv2 24from natsort import natsorted 25from keras.preprocessing import image 26import time 27 28############################################################### 29#residual block 30############################################################### 31 32def residual_block(x, filters_in, filters_out, k_size): 33 shortcut = x 34 x = layers.Conv2D(filters_in, kernel_size=(1, 1), strides=(1, 1), padding="same")(x) 35 x = layers.BatchNormalization()(x) 36 x = layers.LeakyReLU()(x) 37 38 x = layers.Conv2D(filters_in, kernel_size=(k_size, k_size), strides=(1, 1), padding="same")(x) 39 x = layers.BatchNormalization()(x) 40 x = layers.LeakyReLU()(x) 41 42 x = layers.Conv2D(filters_out, kernel_size=(1, 1), strides=(1, 1), padding="same")(x) 43 x = layers.BatchNormalization()(x) 44 45 shortcut_channel = x.shape.as_list()[-1] 46 47 if shortcut_channel != filters_out: 48 shortcut = layers.Conv2D(filters_out, kernel_size=(1, 1), strides=(1, 1), padding="same")(shortcut) 49 50 x = layers.Add()([x, shortcut]) 51 return layers.LeakyReLU()(x) 52 53 54############################################################### 55#residual block 56############################################################### 57mask_num = 4 58input_image = Input(shape=(240,320,3)) 59x = Conv2D(16, (7, 7), padding='same')(input_image) 60x = Conv2D(32, (3, 3), strides = 2, padding='same')(x) 61x = Conv2D(64, (3, 3), strides = 2, padding='same')(x) 62x = residual_block(x , 64, 64, 2) 63x = residual_block(x , 64, 64, 2) 64x = residual_block(x , 64, 64, 2) 65x = UpSampling2D((2, 2))(x) 66x = Conv2D(32, (3, 3), padding='same')(x) 67x = UpSampling2D((2, 2))(x) 68x = Conv2D(16, (3, 3), padding='same')(x) 69x = Conv2D(mask_num, (3, 3), padding='same')(x) 70x = Activation('softmax')(x) 71# x_r = np.array(x) 72# x_r = cv2.bitwise_not(x_r) 73 74residual = Model(input_image,x) 75residual.summary() 76 77 78############################################################### 79#Segmentation 80############################################################### 81 82latent_dim = 1000 83generator_input = Input(latent_dim, name='z_sampling') 84 85x = Dense(latent_dim, activation='relu')(generator_input) 86x = Reshape((15,20,3))(x) 87 88x = BatchNormalization()(x) 89x = UpSampling2D((2, 2))(x) 90x = Conv2D(128, (3, 3), padding='same')(x) 91x = Activation('relu')(x) 92 93x = BatchNormalization()(x) 94x = UpSampling2D((2, 2))(x) 95x = Conv2D(64, (3, 3), padding='same')(x) 96x = Activation('relu')(x) 97 98x = BatchNormalization()(x) 99x = UpSampling2D((2, 2))(x) 100x = Conv2D(32, (3, 3), padding='same')(x) 101 102x = BatchNormalization()(x) 103x = UpSampling2D((2, 2))(x) 104x = Conv2D(3, (3, 3), padding='same')(x) 105x = Activation('sigmoid')(x) 106 107 108generator = Model(generator_input,x) 109generator.summary() 110 111 112lst_mask = [] 113lst_gen = [] 114 115 116for i in range(mask_num): 117 xi = residual.output[:,:,:,i] 118 lst_mask.append(xi) 119 120 121for i in range(mask_num): 122 x = lst_mask[i] 123 124 zi_1 = generator(generator_input)[:,:,:,0] 125 zi_2 = generator(generator_input)[:,:,:,1] 126 zi_3 = generator(generator_input)[:,:,:,2] 127 128 Zi_1 = x*zi_1 129 Zi_2 = x*zi_2 130 Zi_3 = x*zi_3 131 132 Zii_1 = Zi_1[:,:,:,tf.newaxis] 133 Zii_2 = Zi_2[:,:,:,tf.newaxis] 134 Zii_3 = Zi_3[:,:,:,tf.newaxis] 135 136 Zi = tf.concat([Zii_1 ,Zii_2 ,Zii_3 ],axis = 3) 137 138 lst_gen.append(Zi) 139 140x_masked = np.array(lst_gen) 141x_masked = np.sum(x_masked, axis = 0) 142 143x_r = np.array(lst_mask) 144x_r = np.sum(x_r, axis = 0)/mask_num*(-1)+1 145 146x_inf_1 = input_image[:,:,:,0]*x_r 147x_inf_2 = input_image[:,:,:,1]*x_r 148x_inf_3 = input_image[:,:,:,2]*x_r 149 150X_inf_1 = x_inf_1[:,:,:,tf.newaxis] 151X_inf_2 = x_inf_2[:,:,:,tf.newaxis] 152X_inf_3 = x_inf_3[:,:,:,tf.newaxis] 153 154x_inf = tf.concat([X_inf_1,X_inf_2,X_inf_3],axis = 3) 155 156x_out = x_masked + x_inf 157 158mask_gen = Model([input_image,generator_input],x_out) 159mask_gen.summary() 160 161ReDO_optimizer = tf.keras.optimizers.RMSprop(lr=0.0004, clipvalue = 1.0, decay = 1e-8) 162mask_gen.compile(optimizer = ReDO_optimizer , loss = 'binary_crossentropy') 163 164 165 166inputs = Input(shape=(240,320,3)) 167 168 169x = Conv2D(16, (3, 3), padding='same')(inputs) 170x = tf.nn.leaky_relu(x, alpha=0.01, name='Leaky_ReLU') 171x = Dropout(0.25)(x) 172x = Conv2D(16, (3, 3), padding='same')(x) 173x = ZeroPadding2D(padding=((0,1),(1,0)))(x) 174x = tf.nn.leaky_relu(x, alpha=0.01, name='Leaky_ReLU') 175x = Dropout(0.25)(x) 176x = BatchNormalization()(x) 177x = Conv2D(16, (3, 3), padding='same')(x) 178x = tf.nn.leaky_relu(x, alpha=0.01, name='Leaky_ReLU') 179x = Dropout(0.25)(x) 180x = BatchNormalization()(x) 181x = Conv2D(16, (3, 3), padding='same')(x) 182x = tf.nn.leaky_relu(x, alpha=0.01, name='Leaky_ReLU') 183x = Dropout(0.25)(x) 184x = Flatten()(x) 185x = Dense(1)(x) 186x = Activation('sigmoid')(x) 187 188# discriminator 189Discriminator = Model(inputs,x) 190Discriminator.summary() 191discriminator_optimizer = tf.keras.optimizers.RMSprop(lr = 0.0008, clipvalue = 1.0, decay = 1e-8) 192Discriminator.compile(optimizer = discriminator_optimizer, loss = 'binary_crossentropy') 193# redo 194Discriminator.trainable = False 195 196ReDO_input_1 = Input(shape=(240,320,3)) 197ReDO_input_2 = Input(shape=(latent_dim,)) 198 199ReDO_output = Discriminator(mask_gen([ReDO_input_1,ReDO_input_2])) 200ReDO = Model([ReDO_input_1,ReDO_input_2],ReDO_output) 201 202ReDO_optimizer = tf.keras.optimizers.RMSprop(lr=0.0004, clipvalue = 1.0, decay = 1e-8) 203ReDO.compile(optimizer = ReDO_optimizer , loss = 'binary_crossentropy') 204ReDO.summary() 205 206iteration = 5000 +1 207batch_size = 10 208 209base_dir = Path 210 211save_dir_fake = base_dir + '/fig/fake' 212os.makedirs(save_dir_fake,exist_ok = True) 213 214save_dir_real = base_dir + '/fig/real' 215os.makedirs(save_dir_real,exist_ok = True) 216 217data = x_train 218start = 0 219discriminator_loss = [] 220adversarial_loss = [] 221 222for step in range(iteration): 223 224 225 226 random_latent_vectors = np.random.normal(size = (batch_size,latent_dim)) 227 228 stop = start + batch_size 229 230 generated_images = mask_gen.predict([data[start:stop],random_latent_vectors]) 231 real_images = x_train[start:stop] 232 combined_images = np.concatenate([generated_images,real_images]) 233 labels = np.concatenate([np.ones((batch_size,1)),np.zeros((batch_size,1))]) 234 labels += 0.05 * np.random.random(labels.shape) 235 d_loss = Discriminator.train_on_batch(combined_images , labels) 236 237 random_latent_vectors = np.random.normal(size=(batch_size,240,320,3)) 238 239 misleading_targets = np.zeros((batch_size,1)) 240 241 a_loss = ReDO.train_on_batch(random_latent_vectors , misleading_targets) 242 243 start += batch_size 244 if start > len(x_train)-batch_size: 245 start=0 246 247 discriminator_loss.append(d_loss) 248 adversarial_loss.append(a_loss) 249 250 if step%10 == 0: 251 252 print(f'step {step}/{iteration-1}') 253 os.makedirs(base_dir + '/weight', exist_ok = True) 254 GAN_VAE.save_weights(base_dir + '/weight/weights{step}.hdf5') 255 256 print('discriminator loss at step %s: %s' % (step,d_loss)) 257 print('adversarial loss at step %s: %s' % (step,a_loss)) 258 259 img = plt.imshow(generated_images[0]) 260 plt.tick_params(labelbottom=False, labelleft=False, bottom=False, left=False) 261 plt.subplots_adjust(left=0, right=1, bottom=0, top=1) 262 plt.savefig(os.path.join(save_dir_fake, 'gen' + str(step) + '.png'), dpi=300) 263 plt.close() 264 265 img = plt.imshow(real_images[0]) 266 plt.tick_params(labelbottom=False, labelleft=False, bottom=False, left=False) 267 plt.subplots_adjust(left=0, right=1, bottom=0, top=1) 268 plt.savefig(os.path.join(save_dir_real, 'real' + str(step) + '.png'), dpi=300) 269 plt.close() 270 271 272################### 273### Plot losses ### 274################### 275x = np.arange(iteration) 276plt.plot(x, discriminator_loss, "b", label = "Discriminator loss" ) 277plt.plot(x, adversarial_loss , "r", label = "Advsersarial loss") 278plt.title("Losses") 279plt.legend() 280os.makedirs(base_dir + '/fig/loss' ,exist_ok = True) 281plt.savefig(base_dir + '/fig/loss/loss_{iteration-1}.png') 282plt.close() 283 284 285################### 286### make GIF ### 287################### 288 289im_1 = [] 290list_im_1 = natsorted(glob.glob(save_dir_fake+ '/*.png')) 291for images_1 in list_im_1: 292 img_g_1 = Image.open(images_1) 293 im_1.append(img_g_1) 294im_1[0].save(base_dir + f'/gif_{iteration-1}.gif' 295 , save_all = True 296 , append_images = im_1[1:] 297 , optimize = False 298 , duration = 100 299 , loop = 0) 300

このようなエラーがでます

python

1InvalidArgumentError: Input to reshape is a tensor with 10000 values, but the requested shape has 9000 2 [[node model_2/model_1_5/reshape/Reshape (defined at C:\Users\eerg\Anaconda3\lib\site-packages\tensorflow_core\python\framework\ops.py:1751) ]] [Op:__inference_distributed_function_14347] 3

mask_gen.predictに入れるデータが分からないです.
モデルの定義上画像データとノイズを入力するようにしているのですが,うまくいっていないと思われます.
どのようなデータの入れ方をすればよいのでしょうか?

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

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

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

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

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

toast-uz

2020/11/06 11:55

何かのコピペですか?こういうモデルの書き方はあまり見ないので、回答つきにくいと思います。
退会済みユーザー

退会済みユーザー

2020/11/07 02:49

エラーの末尾だけだとさらにコメントがもらいにくくなります。 あと、10000と9000という数字に心当たりはありますか?shapeが合っていなくてエラーが出ている、ですので、恐らくどこかの数字をこねくり回すだけで解決できるタイプのエラーと思います。
siroto

2020/11/09 01:44 編集

すみません.またちゃんと質問がまとまり次第再度質問したいと思います.ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問