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

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

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

関数(ファンクション・メソッド・サブルーチンとも呼ばれる)は、はプログラムのコードの一部であり、ある特定のタスクを処理するように設計されたものです。

Python

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

Q&A

解決済

1回答

5541閲覧

class内の関数を同クラス内の別の関数内で使う方法

trafalbad

総合スコア303

関数

関数(ファンクション・メソッド・サブルーチンとも呼ばれる)は、はプログラムのコードの一部であり、ある特定のタスクを処理するように設計されたものです。

Python

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

0グッド

0クリップ

投稿2017/08/20 00:14

編集2017/08/20 01:34

下記のようにtrain.pyがあります

その上で下記コードを実行するとエラーが出ます。
原理的には合ってるはずなのですが、何故下記エラーが出てしますのでしょうか?

修正させていただきました。回答よろし願いします。

import sys import pickle import numpy as np import tensorflow as tf import os import matplotlib.pyplot as plt import scipy.misc import time from train import DCGAN from layer import show_all_variables def unpickle(file): fp = open(file, 'rb') if sys.version_info.major == 2: data = pickle.load(fp) elif sys.version_info.major == 3: data = pickle.load(fp, encoding='latin-1') fp.close() return data test= unpickle("train_image.pickle") X_image=np.array(test)/127.5 - 1 run_config = tf.ConfigProto() run_config.gpu_options.allow_growth=True with tf.Session(config=run_config) as sess: dcgan = DCGAN(sess, X_image=X_image, epochs=10, step=20) show_all_variables() dcgan.train() --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-16-fb64556ff7b2> in <module>() 3 4 with tf.Session(config=run_config) as sess: ----> 5 dcgan = DCGAN(sess, X_image=X_image, epochs=10, step=20) 6 show_all_variables() 7 dcgan.train() ~/DCGAN-tensorflow/train.py in __init__(self, sess, X_image, epochs, step) 27 self.step = step 28 ---> 29 self.build_model() 30 31 ~/DCGAN-tensorflow/train.py in build_model(self) 35 batch_size=64 36 with tf.variable_scope("discriminator") as scope: ---> 37 h0 = lrelu(conv2d(image, 64, name='d_h0_conv')) 38 h1 = lrelu(batch_norm(conv2d(h0, 128, name='d_h1_conv'),'d_bn1')) 39 h2 = lrelu(batch_norm(conv2d(h1, 256, name='d_h2_conv'),'d_bn2')) NameError: name 'generator' is not defined
train.py # coding: utf-8 # In[1]: import sys import pickle import numpy as np import tensorflow as tf import os import matplotlib.pyplot as plt import scipy.misc import time from layer import * # In[2]: class DCGAN(object): def __init__(self, sess, X_image, epochs, step): self.sess = sess self.X_image=X_image self.epochs = epochs self.step = step self.build_model() def discriminator(self, image): batch_size=64 with tf.variable_scope("discriminator") as scope: h0 = lrelu(conv2d(image, 64, name='d_h0_conv')) h1 = lrelu(batch_norm(conv2d(h0, 128, name='d_h1_conv'),'d_bn1')) h2 = lrelu(batch_norm(conv2d(h1, 256, name='d_h2_conv'),'d_bn2')) h3 = lrelu(batch_norm(conv2d(h2, 512, name='d_h3_conv'),'d_bn3')) # shape=(batch_size, 64, 64, 3) h4 = linear_d(tf.reshape(h3, [batch_size, -1]),2,'d_h4_lin') return h4 # shape=(batch_size, 64, 64, 3) def generator(self, z_): batch_size=64 with tf.variable_scope("generator") as scope: # project `z` and reshape z, h0_w, h0_b = linear(z_, 64*8*4*4, 'g_h0_lin',with_w=True) h0 = tf.nn.relu(batch_norm(tf.reshape(z, [-1, 4, 4, 64*8]), 'g_bn0')) h1, h1_w, h1_b = deconv2d(h0, [batch_size, 8, 8, 64*4], name='g_h1', with_w=True) h1 = tf.nn.relu(batch_norm(h1, 'g_bn1')) h2, h2_w, h2_b = deconv2d(h1, [batch_size, 16, 16, 64*2], name='g_h2', with_w=True) h2 = tf.nn.relu(batch_norm(h2, 'g_bn2')) h3, h3_w, h3_b = deconv2d(h2, [batch_size, 32, 32, 64*1], name='g_h3', with_w=True) h3 = tf.nn.relu(batch_norm(h3, 'g_bn3')) h4, h4_w, h4_b = deconv2d(h3, [batch_size, 64, 64, 3], name='g_h4', with_w=True) return tf.nn.tanh(h4) #shape=(batch_size, 64, 64, 3) def sampler(self, z_):# shape=(batch_size, 64, 64, 3) batch_size=64 with tf.variable_scope("generator") as scope: # project `z` and reshape z= linear(z_, 64*8*4*4,'g_h0_lin') h0 = tf.nn.relu(batch_norm(tf.reshape(z, [-1, 4, 4, 64*8]),'g_bn0',train=False)) h1 = deconv2d(h0, [batch_size, 8, 8, 64*4], name='g_h1') h1 = tf.nn.relu(batch_norm(h1,'g_bn1',train=False)) h2 = deconv2d(h1, [batch_size, 16, 16, 64*2], name='g_h2') h2 = tf.nn.relu(batch_norm(h2,'g_bn2',train=False)) h3 = deconv2d(h2, [batch_size, 32, 32, 64*1], name='g_h3') h3 = tf.nn.relu(batch_norm(h3,'g_bn3',train=False)) h4 = deconv2d(h3, [batch_size, 64, 64, 3], name='g_h4') return tf.nn.tanh(h4) #shape=(batch_size, 64, 64, 3) def build_model(self): self.z = tf.placeholder(tf.float32, [64, 100]) self.image = tf.placeholder(tf.float32, [64, 64, 64, 3]) self.G=self.generator(self.z) #G(z) self.D_logits = self.discriminator(self.image) #D(x) self.sampler = self.sampler(self.z) self.D_logits_ = self.discriminator(self.G) #D(G(z)) batch_label=64 self.d_loss_real = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.D_logits, labels=tf.ones([batch_label], dtype=tf.int64))) self.d_loss_fake = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.D_logits_, labels=tf.zeros([batch_label], dtype=tf.int64))) self.g_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.D_logits_, labels=tf.ones([batch_label], dtype=tf.int64))) self.d_loss = self.d_loss_real + self.d_loss_fake self.d_vars = [var for var in tf.trainable_variables() if 'd_' in var.name] self.g_vars = [var for var in tf.trainable_variables() if 'g_' in var.name] self.saver=tf.train.Saver() def train(self): g_optim = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5).minimize(self.g_loss, var_list=self.g_vars) d_optim = tf.train.AdamOptimizer(learning_rate=0.0002, beta1=0.5).minimize(self.d_loss, var_list=self.d_vars) tf.global_variables_initializer().run() sample_z = np.random.uniform(-1, 1, size=(64, 100)) batch_z = np.random.uniform(-1, 1, [64, 100]) sample_files = self.X_image[0:64] sample = [sample_file for sample_file in sample_files] sample_images = np.array(sample).astype(np.float32) counter=1 start_time=time.time() for epoch in range(self.epochs): batch_idxs= min (len(self.X_image), np.inf) // 64 for idx in range (0, batch_idxs): bacth_files= self.X_image[idx*64:(idx+1)*64] batch = [batch_file for batch_file in bacth_files] batch_images = np.array(batch).astype(np.float32) self.sess.run(d_optim, feed_dict = {self.z: batch_z, self.image: batch_images}) self.sess.run(g_optim, feed_dict = {self.z: batch_z}) # Run g_optim twice to realize loss value self.sess.run(g_optim, feed_dict = {self.z: batch_z}) errD_fake = self.d_loss_fake.eval({self.z: batch_z }) errD_real = self.d_loss_real.eval({self.image: batch_images}) errG = self.g_loss.eval({self.z: batch_z}) counter += 1 print("Epoch: [%2d] [%4d/%4d] time:%4.4f, d_loss: %.8f, g_loss: %.8f" % (epoch, idx, batch_idxs, time.time()-start_time, errD_fake+errD_real, errG)) if np.mod(counter, self.step)==1: samples, d_loss_sample, g_loss_sample = sess.run([self.sampler, self.d_loss, self.g_loss], feed_dict={self.z: sample_z, self.image: sample_images}) print("[Sample] d_loss:%.8f, g_loss:%.8f" % (d_loss_sample, g_loss_sample)) col=8 rows=[] for i in range(8): rows.append(np.hstack(samples[col * i + 0:col * i + col])) vnari=np.vstack(rows) plt.imshow(vnari) plt.show()

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

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

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

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

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

guest

回答1

0

ベストアンサー

NameError: name 'generator' is not defined

このエラーが出るよりも前に別のエラーがたくさん含まれています。まず、動作するコードを提示してください。

想像で修正したコードは以下の様になります。

python

1class staff: 2 def __init__(self,sess): 3 self.sess = sess # 変数名修正 4 self.build() 5 6 def build(self): # 引数selfが必須 7 self.G = self.generator(self.sess) # self.zは存在しないので変更 8 9 def generator(self, z) 10 return z

文法的にはこれで動作はします。

投稿2017/08/20 00:39

shimizukawa

総合スコア1847

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

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

trafalbad

2017/08/20 01:35

コードを追記して質問を修正させていただきました。回答よろしくお願いします
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問