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

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

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

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

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

Q&A

1回答

4114閲覧

dcganを実装したい(コピペ)がエラーが出る

Quad

総合スコア18

Python 3.x

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

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

Python

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

0グッド

0クリップ

投稿2019/07/23 13:39

前提・実現したいこと

このサイトのコードを使って画像生成をしようと考えました!

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

しかしエラーが

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-473f5793b469> in <module>() 262 check_noise=check_noise, 263 r=r, --> 264 c=c 265 ) <ipython-input-14-473f5793b469> in train(self, iterations, batch_size, save_interval, model_interval, check_noise, r, c) 129 # Training Discriminator 130 # ----------------- --> 131 idx = np.random.randint(0, X_train.shape[0], half_batch) 132 133 imgs = X_train[idx] mtrand.pyx in mtrand.RandomState.randint() ValueError: Range cannot be empty (low >= high) unless no samples are taken

該当のソースコード

文字数ぎりぎりなのでimportなど抜いています

python

1np.random.seed(0) 2np.random.RandomState(0) 3tf.set_random_seed(0) 4 5config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)) 6session = tf.Session(config=config) 7tensorflow_backend.set_session(session) 8 9# root_dir = "/home/takusub/PycharmProjects/Samples/dcgan/kill_me_baby_datasets/" 10root_dir = "./" ### keras_dcgan.pyが保存されているディレクトリのフルパス 11input_img_dir = "./proimages" 12save_dir = "./genimages" 13 14class DCGAN(): 15 def __init__(self): 16 17 self.class_names = os.listdir(root_dir) 18 19 self.shape = (128, 128, 3) 20 self.z_dim = 100 21 22 optimizer = Adam(lr=0.0002, beta_1=0.5) 23 24 self.discriminator = self.build_discriminator() 25 self.discriminator.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) 26 27 self.generator = self.build_generator() 28 # self.generator.compile(loss='binary_crossentropy', optimizer=optimizer) 29 30 z = Input(shape=(self.z_dim,)) 31 img = self.generator(z) 32 33 self.discriminator.trainable = False 34 35 valid = self.discriminator(img) 36 37 self.combined = Model(z, valid) 38 self.combined.compile(loss='binary_crossentropy', optimizer=optimizer) 39 40 def build_generator(self): 41 noise_shape = (self.z_dim,) 42 model = Sequential() 43 44 model.add(Dense(128 * 32 * 32, activation="relu", input_shape=noise_shape)) 45 model.add(Reshape((32, 32, 128))) 46 model.add(BatchNormalization(momentum=0.8)) 47 model.add(UpSampling2D()) 48 model.add(Conv2D(128, kernel_size=3, padding="same")) 49 model.add(Activation("relu")) 50 model.add(BatchNormalization(momentum=0.8)) 51 model.add(UpSampling2D()) 52 model.add(Conv2D(64, kernel_size=3, padding="same")) 53 model.add(Activation("relu")) 54 model.add(BatchNormalization(momentum=0.8)) 55 model.add(Conv2D(3, kernel_size=3, padding="same")) 56 model.add(Activation("tanh")) 57 58 model.summary() 59 60 noise = Input(shape=noise_shape) 61 img = model(noise) 62 63 return Model(noise, img) 64 65 def build_discriminator(self): 66 img_shape = self.shape 67 model = Sequential() 68 69 model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=img_shape, padding="same")) 70 model.add(LeakyReLU(alpha=0.2)) 71 model.add(Dropout(0.25)) 72 model.add(Conv2D(64, kernel_size=3, strides=2, padding="same")) 73 model.add(ZeroPadding2D(padding=((0, 1), (0, 1)))) 74 model.add(LeakyReLU(alpha=0.2)) 75 model.add(Dropout(0.25)) 76 model.add(BatchNormalization(momentum=0.8)) 77 model.add(Conv2D(128, kernel_size=3, strides=2, padding="same")) 78 model.add(LeakyReLU(alpha=0.2)) 79 model.add(Dropout(0.25)) 80 model.add(BatchNormalization(momentum=0.8)) 81 model.add(Conv2D(256, kernel_size=3, strides=1, padding="same")) 82 model.add(LeakyReLU(alpha=0.2)) 83 model.add(Dropout(0.25)) 84 85 model.add(Flatten()) 86 model.add(Dense(1, activation='sigmoid')) 87 88 model.summary() 89 90 img = Input(shape=img_shape) 91 validity = model(img) 92 93 return Model(img, validity) 94 95 def build_combined(self): 96 self.discriminator.trainable = False 97 model = Sequential([self.generator, self.discriminator]) 98 99 return model 100 101 def train(self, iterations, batch_size=128, save_interval=50, model_interval=10000, check_noise=None, r=5, c=5): 102 103 X_train, labels = self.load_imgs() 104 105 half_batch = int(batch_size / 2) 106 107 X_train = (X_train.astype(np.float32) - 127.5) / 127.5 108 109 for iteration in range(iterations): 110 111 # ------------------ 112 # Training Discriminator 113 # ----------------- 114 idx = np.random.randint(0, X_train.shape[0], half_batch) 115 116 imgs = X_train[idx] 117 118 noise = np.random.uniform(-1, 1, (half_batch, self.z_dim)) 119 120 gen_imgs = self.generator.predict(noise) 121 122 d_loss_real = self.discriminator.train_on_batch(imgs, np.ones((half_batch, 1))) 123 d_loss_fake = self.discriminator.train_on_batch(gen_imgs, np.zeros((half_batch, 1))) 124 125 d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) 126 127 # ----------------- 128 # Training Generator 129 # ----------------- 130 131 noise = np.random.uniform(-1, 1, (batch_size, self.z_dim)) 132 133 g_loss = self.combined.train_on_batch(noise, np.ones((batch_size, 1))) 134 135 print("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (iteration, d_loss[0], 100 * d_loss[1], g_loss)) 136 137 if iteration % save_interval == 0: 138 self.save_imgs(iteration, check_noise, r, c) 139 start = np.expand_dims(check_noise[0], axis=0) 140 end = np.expand_dims(check_noise[1], axis=0) 141 resultImage = self.visualizeInterpolation(start=start, end=end) 142 # cv2.imwrite("images/latent/" + "latent_{}.png".format(iteration), resultImage) 143 cv2.imwrite(save_dir + "latent_{}.png".format(iteration), resultImage) 144 if iteration % model_interval == 0: 145 # self.generator.save("ganmodels/dcgan-{}-iter.h5".format(iteration)) 146 self.generator.save("mb_dcgan-{}-iter.h5".format(iteration)) 147 148 def save_imgs(self, iteration, check_noise, r, c): 149 noise = check_noise 150 gen_imgs = self.generator.predict(noise) 151 152 # 0-1 rescale 153 gen_imgs = 0.5 * gen_imgs + 0.5 154 155 fig, axs = plt.subplots(r, c) 156 cnt = 0 157 for i in range(r): 158 for j in range(c): 159 axs[i, j].imshow(gen_imgs[cnt, :, :, :]) 160 axs[i, j].axis('off') 161 cnt += 1 162 fig.savefig(save_dir + '%d.png' % iteration) 163 # fig.savefig('images/gen_imgs/kill_me_%d.png' % iteration) 164 165 plt.close() 166 167 def load_imgs(self): 168 169 img_paths = [] 170 labels = [] 171 images = [] 172 # for cl_name in self.class_names: 173 # img_names = os.listdir(os.path.join(root_dir, cl_name)) 174 # for img_name in img_names: 175 # img_paths.append(os.path.abspath(os.path.join(root_dir, cl_name, img_name))) 176 # hot_cl_name = self.get_class_one_hot(cl_name) 177 # labels.append(hot_cl_name) 178 for cl_name in self.class_names: 179 if cl_name == input_img_dir: 180 img_names = os.listdir(os.path.join(root_dir, cl_name)) 181 for img_name in img_names: 182 img_paths.append(os.path.abspath(os.path.join(root_dir, cl_name, img_name))) 183 hot_cl_name = self.get_class_one_hot(cl_name) 184 labels.append(hot_cl_name) 185 186 for img_path in img_paths: 187 img = cv2.imread(img_path) 188 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 189 images.append(img) 190 191 images = np.array(images) 192 193 return (np.array(images), np.array(labels)) 194 195 def get_class_one_hot(self, class_str): 196 label_encoded = self.class_names.index(class_str) 197 198 label_hot = np_utils.to_categorical(label_encoded, len(self.class_names)) 199 label_hot = label_hot 200 201 return label_hot 202 203 def visualizeInterpolation(self, start, end, save=True, nbSteps=10): 204 print("Generating interpolations...") 205 206 steps = nbSteps 207 latentStart = start 208 latentEnd = end 209 210 startImg = self.generator.predict(latentStart) 211 endImg = self.generator.predict(latentEnd) 212 213 vectors = [] 214 215 alphaValues = np.linspace(0, 1, steps) 216 for alpha in alphaValues: 217 vector = latentStart * (1 - alpha) + latentEnd * alpha 218 vectors.append(vector) 219 220 vectors = np.array(vectors) 221 222 resultLatent = None 223 resultImage = None 224 225 for i, vec in enumerate(vectors): 226 gen_img = np.squeeze(self.generator.predict(vec), axis=0) 227 gen_img = (0.5 * gen_img + 0.5) * 255 228 interpolatedImage = cv2.cvtColor(gen_img, cv2.COLOR_RGB2BGR) 229 interpolatedImage = interpolatedImage.astype(np.uint8) 230 resultImage = interpolatedImage if resultImage is None else np.hstack([resultImage, interpolatedImage]) 231 232 return resultImage 233 234 235if __name__ == '__main__': 236 dcgan = DCGAN() 237 r, c = 2,2 238 check_noise = np.random.uniform(-1, 1, (r * c, 100)) 239 dcgan.train( 240 iterations=200000, 241 batch_size=32, 242 # save_interval=1000, 243 save_interval=50, ### epoch回数が50の倍数になったときに、generator生成画像を保存 244 model_interval=5000, 245 check_noise=check_noise, 246 r=r, 247 c=c 248 )

試したこと

調べると、X_train.shape[0]が存在しないのが原因なのではないかと思いました。
しかしX_train.shape[0]なんてどこで使うのかが分かりません

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

python3,google colaboratory

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

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

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

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

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

guest

回答1

0

あなたが画像を持っていないのではないでしょうか。
もしそうだとしたら
X_train.shape[0]は0が返されるとおもうので

python

1np.random.randinit(0,0,)

となってしまい
0から0の範囲を指定してしまうことになり

error

1mtrand.pyx in mtrand.RandomState.randint() 2 3ValueError: Range cannot be empty (low >= high) unless no samples are taken

とエラーが出る原因になっていると思います。

投稿2019/07/23 22:09

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

Quad

2019/07/24 00:29

エラーの意味は分かりました。ありがとうございます。 しかし画像を持っていないというのはどう解決すればよいのでしょうか 一応画像はcolabにアップロードしているはずなのですが
退会済みユーザー

退会済みユーザー

2019/07/24 01:03

すみません。 colabがわからにのですが、 img_pathに画像のパスをついかしていき for img_path in img_paths: img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) images.append(img) images = np.array(images) return (np.array(images), np.array(labels)) をすればいいのではないでしょうか。 要するに、load_imgsを書き換えればいいと思います。
Quad

2019/07/24 03:57

それを書くと --------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-18-7a9f7b061e7f> in <module>() 302 check_noise=check_noise, 303 r=r, --> 304 c=c 305 ) 1 frames <ipython-input-18-7a9f7b061e7f> in load_imgs(self) 243 for img_path in img_paths: 244 img = cv2.imread(img_path) --> 245 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 246 images.append(img) 247 error: OpenCV(3.4.3) /io/opencv/modules/imgproc/src/color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' というエラーが出てしまいました。
退会済みユーザー

退会済みユーザー

2019/07/24 07:56

すみません。 これ以上わからないです。 解決できなくてすみません。
Quad

2019/07/24 13:29

ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問