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

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

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

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

Python

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

Q&A

1回答

1161閲覧

機械学習コードエラー対策をお願いします。

watchdogs

総合スコア54

機械学習

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

Python

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

0グッド

0クリップ

投稿2021/02/13 05:35

下記の様なエラーが出て困っています。
解決策をおしてえて頂けますか。

ayers.py", line 31, in <module>
TF_GRAPHKEYS_VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES
AttributeError: module 'tensorflow' has no attribute 'GraphKeys'

Python

1import tensorflow.compat.v1 as tf 2import os 3import re 4import time 5import nltk 6import re 7import string 8import tensorlayer as tl 9from utils import * 10 11 12dataset = '102flowers' # 13need_256 = True # set to True for stackGAN 14 15 16 17if dataset == '102flowers': 18 """ 19 images.shape = [8000, 64, 64, 3] 20 captions_ids = [80000, any] 21 """ 22 cwd = os.getcwd() 23 img_dir = os.path.join(cwd, '102flowers') 24 caption_dir = os.path.join(cwd, 'text_c10') 25 VOC_FIR = cwd + '/vocab.txt' 26 27 ## load captions 28 caption_sub_dir = load_folder_list( caption_dir ) 29 captions_dict = {} 30 processed_capts = [] 31 for sub_dir in caption_sub_dir: # get caption file list 32 with tl.ops.suppress_stdout(): 33 files = tl.files.load_file_list(path=sub_dir, regx='^image_[0-9]+.txt')# 34 for i, f in enumerate(files): 35 file_dir = os.path.join(sub_dir, f) 36 key = int(re.findall('\d+', f)[0]) 37 t = open(file_dir,'r') 38 lines = [] 39 for line in t: 40 line = preprocess_caption(line) 41 lines.append(line) 42 processed_capts.append(tl.nlp.process_sentence(line, start_word="<S>", end_word="</S>")) 43 assert len(lines) == 10, "Every flower image have 10 captions" 44 captions_dict[key] = lines 45 print(" * %d x %d captions found " % (len(captions_dict), len(lines))) 46 47 ## build vocab 48 if not os.path.isfile('vocab.txt'): 49 _ = tl.nlp.create_vocab(processed_capts, word_counts_output_file=VOC_FIR, min_word_count=1) 50 else: 51 print("WARNING: vocab.txt already exists") 52 vocab = tl.nlp.Vocabulary(VOC_FIR, start_word="<S>", end_word="</S>", unk_word="<UNK>") 53 54 ## store all captions ids in list 55 captions_ids = [] 56 try: # python3 57 tmp = captions_dict.items() 58 except: # python3 59 tmp = captions_dict.iteritems() 60 for key, value in tmp: 61 for v in value: 62 captions_ids.append( [vocab.word_to_id(word) for word in nltk.tokenize.word_tokenize(v)] + [vocab.end_id]) # add END_ID 63 # print(v) # prominent purple stigma,petals are white inc olor 64 # print(captions_ids) # [[152, 19, 33, 15, 3, 8, 14, 719, 723]] 65 # exit() 66 captions_ids = np.asarray(captions_ids) 67 print(" * tokenized %d captions" % len(captions_ids)) 68 69 ## check 70 img_capt = captions_dict[1][1] 71 print("img_capt: %s" % img_capt) 72 print("nltk.tokenize.word_tokenize(img_capt): %s" % nltk.tokenize.word_tokenize(img_capt)) 73 img_capt_ids = [vocab.word_to_id(word) for word in nltk.tokenize.word_tokenize(img_capt)]#img_capt.split(' ')] 74 print("img_capt_ids: %s" % img_capt_ids) 75 print("id_to_word: %s" % [vocab.id_to_word(id) for id in img_capt_ids]) 76 77 ## load images 78 with tl.ops.suppress_stdout(): # get image files list 79 imgs_title_list = sorted(tl.files.load_file_list(path=img_dir, regx='^image_[0-9]+.jpg')) 80 print(" * %d images found, start loading and resizing ..." % len(imgs_title_list)) 81 s = time.time() 82 83 # time.sleep(10) 84 # def get_resize_image(name): # fail 85 # img = scipy.misc.imread( os.path.join(img_dir, name) ) 86 # img = tl.prepro.imresize(img, size=[64, 64]) # (64, 64, 3) 87 # img = img.astype(np.float32) 88 # return img 89 # images = tl.prepro.threading_data(imgs_title_list, fn=get_resize_image) 90 images = [] 91 images_256 = [] 92 for name in imgs_title_list: 93 # print(name) 94 img_raw = scipy.misc.imread( os.path.join(img_dir, name) ) 95 img = tl.prepro.imresize(img_raw, size=[64, 64]) # (64, 64, 3) 96 img = img.astype(np.float32) 97 images.append(img) 98 if need_256: 99 img = tl.prepro.imresize(img_raw, size=[256, 256]) # (256, 256, 3) 100 img = img.astype(np.float32) 101 102 images_256.append(img) 103 # images = np.array(images) 104 # images_256 = np.array(images_256) 105 print(" * loading and resizing took %ss" % (time.time()-s)) 106 107 n_images = len(captions_dict) 108 n_captions = len(captions_ids) 109 n_captions_per_image = len(lines) # 10 110 111 print("n_captions: %d n_images: %d n_captions_per_image: %d" % (n_captions, n_images, n_captions_per_image)) 112 113 captions_ids_train, captions_ids_test = captions_ids[: 8000*n_captions_per_image], captions_ids[8000*n_captions_per_image :] 114 images_train, images_test = images[:8000], images[8000:] 115 if need_256: 116 images_train_256, images_test_256 = images_256[:8000], images_256[8000:] 117 n_images_train = len(images_train) 118 n_images_test = len(images_test) 119 n_captions_train = len(captions_ids_train) 120 n_captions_test = len(captions_ids_test) 121 print("n_images_train:%d n_captions_train:%d" % (n_images_train, n_captions_train)) 122 print("n_images_test:%d n_captions_test:%d" % (n_images_test, n_captions_test)) 123 124 ## check test image 125 # idexs = get_random_int(min=0, max=n_captions_test-1, number=64) 126 # temp_test_capt = captions_ids_test[idexs] 127 # for idx, ids in enumerate(temp_test_capt): 128 # print("%d %s" % (idx, [vocab.id_to_word(id) for id in ids])) 129 # temp_test_img = images_train[np.floor(np.asarray(idexs).astype('float')/n_captions_per_image).astype('int')] 130 # save_images(temp_test_img, [8, 8], 'temp_test_img.png') 131 # exit() 132 133 # ## check the first example 134 # tl.visualize.frame(I=images[0], second=5, saveable=True, name='temp', cmap=None) 135 # for cap in captions_dict[1]: 136 # print(cap) 137 # print(captions_ids[0:10]) 138 # for ids in captions_ids[0:10]: 139 # print([vocab.id_to_word(id) for id in ids]) 140 # print_dict(captions_dict) 141 142 # ## generate a random batch 143 # batch_size = 64 144 # idexs = get_random_int(0, n_captions_test, batch_size) 145 # # idexs = [i for i in range(0,100)] 146 # print(idexs) 147 # b_seqs = captions_ids_test[idexs] 148 # b_images = images_test[np.floor(np.asarray(idexs).astype('float')/n_captions_per_image).astype('int')] 149 # print("before padding %s" % b_seqs) 150 # b_seqs = tl.prepro.pad_sequences(b_seqs, padding='post') 151 # print("after padding %s" % b_seqs) 152 # # print(input_images.shape) # (64, 64, 64, 3) 153 # for ids in b_seqs: 154 # print([vocab.id_to_word(id) for id in ids]) 155 # print(np.max(b_images), np.min(b_images), b_images.shape) 156 # from utils import * 157 # save_images(b_images, [8, 8], 'temp2.png') 158 # # tl.visualize.images2d(b_images, second=5, saveable=True, name='temp2') 159 # exit() 160 161import pickle 162def save_all(targets, file): 163 with open(file, 'wb') as f: 164 pickle.dump(targets, f) 165 166save_all(vocab, '_vocab.pickle') 167save_all((images_train_256, images_train), '_image_train.pickle') 168save_all((images_test_256, images_test), '_image_test.pickle') 169save_all((n_captions_train, n_captions_test, n_captions_per_image, n_images_train, n_images_test), '_n.pickle') 170save_all((captions_ids_train, captions_ids_test), '_caption.pickle') 171

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

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

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

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

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

meg_

2021/02/13 07:36

エラー発生箇所はどこですか?
watchdogs

2021/02/13 11:48

files = tl.files.load_file_list(path=sub_dir, regx='^image_[0-9]+\.txt') 33行目です
meg_

2021/02/14 01:47

情報は質問に追記してください。
toast-uz

2021/02/14 02:31

コードの引用元があれば教えて下さい。またエラーは一部を切り出さずに、スタックトレース全体を記述してください。
guest

回答1

0

検索してみると、以下のように書かれています。

import tensorflow as tf

import tensorflow.compat.v1 as tf

に変更しなさい。

Tensorflow 2.1.0 Error, module 'tensorflow' has no attribute 'GraphKeys'

追加で調べて見ました。

tensorflowを明示的にimportしていませんが、
import tensorlayer as tl
の中で、import tensorflow as tfが実行されています。
具体的には、以下のファイルなどです。
C:\Users\XXX\anaconda3\envs\py37\lib\site-packages\tensorlayer\layers\activation.py

pythonのimportは、同じ名前のモジュールやパッケージは複数回importすると、最初にimportしたものが有効になるので、先に
import tensorflow.compat.v1 as tf
をしておけば大丈夫かと思ったのですが、tensorflowとtensorflow.compat.v1はモジュール名が違うのでどちらもimport出来てしまいます。

python

1>>> import tensorflow as tf2 2>>> import tensorflow.compat.v1 as tf1 3>>> print(tf2) 4<module 'tensorflow' from 'C:\Users\XXX\anaconda3\envs\py37\lib\site-packages\tensorflow\__init__.py'> 5>>> print(tf1) 6<module 'tensorflow.compat.v1' from 'C:\Users\XXX\anaconda3\envs\py37\lib\site-packages\tensorflow\_api\v2\compat\v1\__init__.py'>

このため、
TF_GRAPHKEYS_VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES
が実行されている layers.pyの中ではtensorflow ver.2のものが使われてエラーを
出しています。

tensorlayerがtensorflow ver.2に隊押していないのかと思ってドキュメントを見てみましたが、Welcome to TensorLayerを見ても、tensorflow ver.2に対応していないとは書かれていません。

ここからは推測になりますが、tensorlayerのバージョンが古いのではないでしょうか。

投稿2021/02/13 05:42

編集2021/02/13 07:37
ppaul

総合スコア24666

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

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

watchdogs

2021/02/13 06:37

返答ありがとうございます。 私も調べましたが、 import tensorflow as tf つかってないんですよね。
ppaul

2021/02/13 07:38

tensorlayerのバージョンを調べて見て下さい。 回答に追加しました。
ppaul

2021/02/13 08:52

こちらで調べたtensorlayerのバージョンは以下でした。 > pip show tensorlayer Name: tensorlayer Version: 2.2.3 Summary: High Level Tensorflow Deep Learning Library for Researcher and Engineer. Home-page: https://github.com/tensorlayer/tensorlayer Author: TensorLayer Contributors Author-email: tensorlayer@gmail.com License: apache Location: c:\users\shinp\anaconda3\envs\py37\lib\site-packages Requires: wrapt, numpy, scikit-learn, scipy, cloudpickle, scikit-image, requests, imageio, h5py, progressbar2 Required-by:
watchdogs

2021/02/13 11:46 編集

tensorlayer2.2.3をいれてもダメですね。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問