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

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

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

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

Q&A

1回答

562閲覧

No such file or directoryのエラーをなくす

gamdam

総合スコア10

Python 3.x

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

0グッド

0クリップ

投稿2022/11/28 03:33

前提

No such file or directoryのエラーをなくしたいです。

実現したいこと

https://qiita.com/jovyan/items/d646c74b14a1feaf5acd
上記のサイトに載っているBERTのプログラムを実行したいです。
GoogleColabを用いています。

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

FileNotFoundError Traceback (most recent call last) <ipython-input-40-2d5a6b7aa059> in <module> 2 for i in range(12): 3 emb1 = extract_bert_embeddings('./bert_embeddings1.jsonl', ----> 4 target_layer=i, target_token=target_words[0]) 5 emb2 = extract_bert_embeddings('./bert_embeddings2.jsonl', 6 target_layer=i, target_token=target_words[1]) <ipython-input-36-e043170bcc6c> in extract_bert_embeddings(input_path, target_token, target_layer) 1 def extract_bert_embeddings(input_path, target_token, target_layer=10): ----> 2 with open(input_path, 'r') as f: 3 output_jsons = f.readlines() 4 5 embs = [] FileNotFoundError: [Errno 2] No such file or directory: './bert_embeddings1.jsonl'

該当のソースコード

python

1import json 2import numpy as np 3import matplotlib.pyplot as plt 4import seaborn as sns 5 6# matplotlibで日本語を使うためのライブラリ 7!pip install japanize_matplotlib 8import japanize_matplotlib 9 10# Google Driveをマウント 11from google.colab import drive 12drive.mount('/content/drive') 13 14# MeCabインストール 15!apt install aptitude swig 16!aptitude install mecab libmecab-dev mecab-ipadic-utf8 git make curl xz-utils file -y 17 18# NEologd辞書インストール 19%cd /content 20!git clone --depth 1 https://github.com/neologd/mecab-ipadic-neologd.git 21%cd mecab-ipadic-neologd 22!echo yes | ./bin/install-mecab-ipadic-neologd -n 23 24# pythonでMeCabを呼び出すためのライブラリをインストール 25!pip install mecab-python3 26!pip install unidic-lite # これがないとmecab-python3実行時にエラーが出る 27import MeCab 28 29!apt install aptitude 30!aptitude install mecab libmecab-dev mecab-ipadic-utf8 git make curl xz-utils file -y 31!pip install mecab-python3 32 33!git clone --depth 1 https://github.com/neologd/mecab-ipadic-neologd.git 34!echo yes | mecab-ipadic-neologd/bin/install-mecab-ipadic-neologd -n 35 36!ln -s /etc/mecabrc /usr/local/etc/mecabrc 37 38target_words = ["結構", "失敬", "無心", "首"] 39 40texts1 = ["初めてクッキーを作ったけど、難しくなかったし、結構おいしく作れたと思う。", 41 "彼は口には出さないけど、背が小さいことをを結構気にしています。", 42 "あそこのレストランは、安いのに結構おいしいんですよ。", 43 "トイレのあとで、手を洗わない人は結構たくさんいます。", 44 "もう十分いただきました。これ以上は結構です。", 45 "そんなことまでしていただかなくても結構です。", 46 "この際には土地はいただかないことにして、金でお願いができますれば結構だと存じていたのでございますが。", 47 "それでも、先生はほかの人と違って、遊びながらお仕事が出来るので結構でございます。"] 48 49texts2 = ["昨晩はお見苦しいところをお見せして失敬しました。", 50 "全体あなたがたはこんな失敬なことを言っていて、自分では気がつかんのですか。", 51 "失敬な発言ばかりが口をついて出てしまう彼は、案の定職場で上手くいかず、すぐに辞めてしまった。", 52 "何を言うんだ。失敬な事を言うな。ここは、お前たちの来るところでは無い。帰れ!", 53 "兄の本棚からちょっと失敬してきた。", 54 "このボールペンを失敬させてもらいますね。", 55 "一人の学生が巡査の帽子を失敬して一目散に走り出した。", 56 "さて退出するときに、彼はテーブルから自分のものでない手紙を失敬して行ったのですよ。"] 57 58texts3 = ["月の輝きを無心に眺めているうちに、天吾の中に古代から受け継がれてきた記憶のようなものが呼び起こされていった。", 59 "波の音は、無心に、終日岸の岩角にぶつかって、砕けて、しぶきをあげていました。。", 60 "そして、この努力を無心に続ければいつかはなにか突破口につながると思いたかった。", 61 "すすきの花の向い火や、きらめく赤褐の樹立のなかに、鹿が無心に遊んでいます。", 62 "これを訪ね身の振り方を相談した途端に、姉の亭主に、三百円の無心をされた。", 63 "そのとき、ちょうど門口へ乳飲子をおぶった女こじきが立って、無心をねがったのでした。", 64 "逮捕された男の母親が取材に対し、容疑者から前日に金を無心され暴行されていたことを明らかにしました。", 65 "その結果はちょいちょい耕太郎が無心の手紙を持たされて、一里の道を老父の処へ使いにやらされた。", ] 66 67texts4 = ["首をかたむけた時に邪魔になるので、髪の毛はいつもしばっています。", 68 "首を後ろに反らせながら、引きつったような声で笑う。", 69 "長めな首の美しさを引き立てるためか、洋服の襟に白い飾りがあった。", 70 "従業員は眉を少ししかめ、考えを巡らせ、それから丁寧に首を横に振った。", 71 "労働災害による休業中の労働者を、首にすることはできません。", 72 "このプロジェクトには、このチーム一人一人の首がかかっている。", 73 "首になりたくなければ、ちゃんと成果を上げろ!", 74 "会社を首にされたが、家族には言い出せず、毎日会社に行くふりをして公園で過ごしている。"] 75 76with open('texts1.txt', mode='w') as f: 77 f.write('\n'.join(texts1)) 78with open('texts2.txt', mode='w') as f: 79 f.write('\n'.join(texts2)) 80with open('texts3.txt', mode='w') as f: 81 f.write('\n'.join(texts3)) 82with open('texts4.txt', mode='w') as f: 83 f.write('\n'.join(texts4)) 84 85def mecab_tokenizer(texts, 86 dict_path="/usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd"): 87 mecab = MeCab.Tagger("-Owakati -d " + dict_path) 88 token_list = [] 89 for s in texts: 90 parsed = mecab.parse(s).replace('\n', '') 91 token_list += [parsed.split()] 92 return token_list 93 94%tensorflow_version 2.x 95import tensorflow as tf 96 97!git clone https://github.com/google-research/bert.git 98 99def convert_tokens_to_ids(vocab, tokens): 100 # modify so that it returns id=1 which means [UNK] when a token is not in vocab 101 output = [] 102 for t in tokens: 103 if t in vocab.keys(): 104 i = vocab[t] 105 else: # if t is [UNK] 106 i = 1 107 output.append(i) 108 return output 109 110class FullTokenizer(object): 111 """Runs end-to-end tokenziation.""" 112 113 def __init__(self, vocab_file, do_lower_case=True): 114 self.vocab = load_vocab(vocab_file) 115 self.inv_vocab = {v: k for k, v in self.vocab.items()} 116 #self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) 117 #self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) 118 # use Mecab 119 self.mecab_tokenizer = MecabTokenizer() 120 121 def tokenize(self, text): 122 split_tokens = [] 123 # for token in self.basic_tokenizer.tokenize(text): 124 # use Mecab 125 for token in self.mecab_tokenizer.tokenize(text): 126 split_tokens.append(token) 127 128 return split_tokens 129 130 def convert_tokens_to_ids(self, tokens): 131 #return convert_by_vocab(self.vocab, tokens) 132 return convert_tokens_to_ids(self.vocab, tokens) 133 134 def convert_ids_to_tokens(self, ids): 135 return convert_by_vocab(self.inv_vocab, ids) 136 137# BERT実行 138for i in range(1, 5): 139 input_file = 'texts' + str(i) + '.txt' 140 output_file = 'bert_embeddings' + str(i) + '.jsonl' 141 142 !python ./bert/extract_features_mecab_neologd.py \ 143 --input_file=$input_file \ 144 --output_file=$output_file \ 145 --vocab_file=./BERT_base_stockmark/vocab.txt \ 146 --bert_config_file=./BERT_base_stockmark/bert_config.json \ 147 --init_checkpoint=./BERT_base_stockmark/output_model.ckpt \ 148 --layers 0,1,2,3,4,5,6,7,8,9,10,11 149 150def extract_bert_embeddings(input_path, target_token, target_layer=10): 151 with open(input_path, 'r') as f: 152 output_jsons = f.readlines() 153 154 embs = [] 155 for output_json in output_jsons: 156 output = json.loads(output_json) 157 for feature in output['features']: 158 if feature['token'] != target_token: continue 159 for layer in feature['layers']: 160 if layer['index'] != target_layer: continue 161 embs.append(layer['values']) 162 return np.array(embs) 163 164bert_embeddings = [] 165for i in range(12): 166 emb1 = extract_bert_embeddings('./bert_embeddings1.jsonl', 167 target_layer=i, target_token=target_words[0]) 168 emb2 = extract_bert_embeddings('./bert_embeddings2.jsonl', 169 target_layer=i, target_token=target_words[1]) 170 emb3 = extract_bert_embeddings('./bert_embeddings3.jsonl', 171 target_layer=i, target_token=target_words[2]) 172 emb4 = extract_bert_embeddings('./bert_embeddings4.jsonl', 173 target_layer=i, target_token=target_words[3]) 174 embeddings = np.vstack([emb1, emb2, emb3, emb4]) 175 bert_embeddings.append(embeddings) 176bert_embeddings = np.array(bert_embeddings)

試したこと

MyDriveのBERT_base_stockmarkの中にbert_embeddings*.jsonlというファイルを作成しましたがエラーがなくなりませんでした

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

ここにより詳細な情報を記載してください。

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

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

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

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

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

guest

回答1

0

ご存知だろうとは思いますが、みつからないと言われているファイルは以下のブロック(このあとも続いています)で作成されるものです。

python

1# BERT実行 2for i in range(1, 5): 3 input_file = 'texts' + str(i) + '.txt' 4 output_file = 'bert_embeddings' + str(i) + '.jsonl'

この部分を実行していないか、実行時にエラーになっているのではないでしょうか。

投稿2022/11/28 05:17

TakaiY

総合スコア12745

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

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

gamdam

2022/11/28 06:24

t open file './bert/extract_features_mecab_neologd.py': [Errno 2] No such file or directory python3: can't open file './bert/extract_features_mecab_neologd.py': [Errno 2] No such file or directory python3: can't open file './bert/extract_features_mecab_neologd.py': [Errno 2] No such file or directory python3: can't open file './bert/extract_features_mecab_neologd.py': [Errno 2] No such file or directory というエラーが出てしまいました
TakaiY

2022/11/28 06:48

そこに書いてあるファイルが無いということです。 手順のなかのどこかで作られるか、ほかのところから持ってくるのでしょう。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問