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

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

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

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

Q&A

解決済

1回答

1521閲覧

自分でニューラルネットワークを作ろうのプログラムをGoogleCollaboratoryで動かしたい。

退会済みユーザー

退会済みユーザー

総合スコア0

Python

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

0グッド

1クリップ

投稿2021/03/20 00:16

編集2021/03/20 07:47

https://qiita.com/takahiro_itazuri/items/d2bea1c643d7cca11352
プログラムはここを参考にしたのですが、以下そのまま転載。

python

1from google.colab import drive 2drive.mount('/content/drive') 3 4import sys 5sys.path.append('/content/drive/My Drive/colab') 6 7import numpy as np 8import ActivationFunction as AF 9 10# 3層ニューラルネットワーク 11class ThreeLayerNetwork: 12 # コンストラクタ 13 def __init__(self, inodes, hnodes, onodes, lr): 14 # 各レイヤーのノード数 15 self.inodes = inodes 16 self.hnodes = hnodes 17 self.onodes = onodes 18 19 # 学習率 20 self.lr = lr 21 22 # 重みの初期化 23 self.w_ih = np.random.normal(0.0, 1.0, (self.hnodes, self.inodes)) 24 self.w_ho = np.random.normal(0.0, 1.0, (self.onodes, self.hnodes)) 25 26 # 活性化関数 27 self.af = AF.sigmoid 28 self.daf = AF.derivative_sigmoid 29 30 # 誤差逆伝搬 31 def backprop(self, idata, tdata): 32 # 縦ベクトルに変換 33 o_i = np.array(idata, ndmin=2).T 34 t = np.array(tdata, ndmin=2).T 35 36 # 隠れ層 37 x_h = np.dot(self.w_ih, o_i) 38 o_h = self.af(x_h) 39 40 # 出力層 41 x_o = np.dot(self.w_ho, o_h) 42 o_o = self.af(x_o) 43 44 # 誤差計算 45 e_o = (t - o_o) 46 e_h = np.dot(self.w_ho.T, e_o) 47 48 # 重みの更新 49 self.w_ho += self.lr * np.dot((e_o * self.daf(o_o)), o_h.T) 50 self.w_ih += self.lr * np.dot((e_h * self.daf(o_h)), o_i.T) 51 52 53 # 順伝搬 54 def feedforward(self, idata): 55 # 入力のリストを縦ベクトルに変換 56 o_i = np.array(idata, ndmin=2).T 57 58 # 隠れ層 59 x_h = np.dot(self.w_ih, o_i) 60 o_h = self.af(x_h) 61 62 # 出力層 63 x_o = np.dot(self.w_ho, o_h) 64 o_o = self.af(x_o) 65 66 return o_o 67 68if __name__=='__main__': 69 # パラメータ 70 inodes = 784 71 hnodes = 100 72 onodes = 10 73 lr = 0.3 74 75 # ニューラルネットワークの初期化 76 nn = ThreeLayerNetwork(inodes, hnodes, onodes, lr) 77 78 # トレーニングデータのロード 79 training_data_file = open('mnist_dataset/mnist_train.csv', 'r') 80 training_data_list = training_data_file.readlines() 81 training_data_file.close() 82 83 # テストデータのロード 84 test_data_file = open('mnist_dataset/mnist_test.csv') 85 test_data_list = test_data_file.readlines() 86 test_data_file.close() 87 88 # 学習 89 epoch = 10 90 for e in range(epoch): 91 print('#epoch ', e) 92 data_size = len(training_data_list) 93 for i in range(data_size): 94 if i % 1000 == 0: 95 print(' train: {0:>5d} / {1:>5d}'.format(i, data_size)) 96 val = training_data_list[i].split(',') 97 idata = (np.asfarray(val[1:]) / 255.0 * 0.99) + 0.01 98 tdata = np.zeros(onodes) + 0.01 99 tdata[int(val[0])] = 0.99 100 nn.backprop(idata, tdata) 101 pass 102 pass 103 104 # テスト 105 scoreboard = [] 106 for record in test_data_list: 107 val = record.split(',') 108 idata = (np.asfarray(val[1:]) / 255.0 * 0.99) + 0.01 109 tlabel = int(val[0]) 110 predict = nn.feedforward(idata) 111 plabel = np.argmax(predict) 112 scoreboard.append(tlabel == plabel) 113 pass 114 115 scoreboard_array = np.asarray(scoreboard) 116 print('performance: ', scoreboard_array.sum() / scoreboard_array.size)

これをそのままGoogleCollaboratoryにコピペして実行しても、

Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).

ModuleNotFoundError Traceback (most recent call last)
<ipython-input-5-21a5c5cca7e6> in <module>()
6
7 import numpy as np
----> 8 import ActivationFunction as AF
9
10 # 3層ニューラルネットワーク

ModuleNotFoundError: No module named 'ActivationFunction'


NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.

と出ます、どうすれば良いでしょうか?

また、パスは
https://blog.mktia.com/file-access-from-colab-to-google-drive/
ここを参考に、そのまま書きました、そのままなので間違ってると思います。

デスクトップ上ではできます。

できました、ありがとうございます、以下にコード書きます、皆さん使ってみて下さい。

python

1import sys 2 3from google.colab import drive 4drive.mount('/content/drive') 5 6sys.path.append('/content/drive/My Drive') 7 8import numpy as np 9import ActivationFunction as AF 10 11# 3層ニューラルネットワーク 12class ThreeLayerNetwork: 13 # コンストラクタ 14 def __init__(self, inodes, hnodes, onodes, lr): 15 # 各レイヤーのノード数 16 self.inodes = inodes 17 self.hnodes = hnodes 18 self.onodes = onodes 19 20 # 学習率 21 self.lr = lr 22 23 # 重みの初期化 24 self.w_ih = np.random.normal(0.0, 1.0, (self.hnodes, self.inodes)) 25 self.w_ho = np.random.normal(0.0, 1.0, (self.onodes, self.hnodes)) 26 27 # 活性化関数 28 self.af = AF.sigmoid 29 self.daf = AF.derivative_sigmoid 30 31 # 誤差逆伝搬 32 def backprop(self, idata, tdata): 33 # 縦ベクトルに変換 34 o_i = np.array(idata, ndmin=2).T 35 t = np.array(tdata, ndmin=2).T 36 37 # 隠れ層 38 x_h = np.dot(self.w_ih, o_i) 39 o_h = self.af(x_h) 40 41 # 出力層 42 x_o = np.dot(self.w_ho, o_h) 43 o_o = self.af(x_o) 44 45 # 誤差計算 46 e_o = (t - o_o) 47 e_h = np.dot(self.w_ho.T, e_o) 48 49 # 重みの更新 50 self.w_ho += self.lr * np.dot((e_o * self.daf(o_o)), o_h.T) 51 self.w_ih += self.lr * np.dot((e_h * self.daf(o_h)), o_i.T) 52 53 54 # 順伝搬 55 def feedforward(self, idata): 56 # 入力のリストを縦ベクトルに変換 57 o_i = np.array(idata, ndmin=2).T 58 59 # 隠れ層 60 x_h = np.dot(self.w_ih, o_i) 61 o_h = self.af(x_h) 62 63 # 出力層 64 x_o = np.dot(self.w_ho, o_h) 65 o_o = self.af(x_o) 66 67 return o_o 68 69if __name__=='__main__': 70 # パラメータ 71 inodes = 784 72 hnodes = 100 73 onodes = 10 74 lr = 0.3 75 76 # ニューラルネットワークの初期化 77 nn = ThreeLayerNetwork(inodes, hnodes, onodes, lr) 78 79 # トレーニングデータのロード 80 training_data_file = open('drive/My Drive/mnist_dataset/mnist_train.csv', 'r') 81 training_data_list = training_data_file.readlines() 82 training_data_file.close() 83 84 # テストデータのロード 85 test_data_file = open('drive/My Drive/mnist_dataset/mnist_test.csv') 86 test_data_list = test_data_file.readlines() 87 test_data_file.close() 88 89 # 学習 90 epoch = 10 91 for e in range(epoch): 92 print('#epoch ', e) 93 data_size = len(training_data_list) 94 for i in range(data_size): 95 if i % 1000 == 0: 96 print(' train: {0:>5d} / {1:>5d}'.format(i, data_size)) 97 val = training_data_list[i].split(',') 98 idata = (np.asfarray(val[1:]) / 255.0 * 0.99) + 0.01 99 tdata = np.zeros(onodes) + 0.01 100 tdata[int(val[0])] = 0.99 101 nn.backprop(idata, tdata) 102 pass 103 pass 104 105 # テスト 106 scoreboard = [] 107 for record in test_data_list: 108 val = record.split(',') 109 idata = (np.asfarray(val[1:]) / 255.0 * 0.99) + 0.01 110 tlabel = int(val[0]) 111 predict = nn.feedforward(idata) 112 plabel = np.argmax(predict) 113 scoreboard.append(tlabel == plabel) 114 pass 115 116 scoreboard_array = np.asarray(scoreboard) 117 print('performance: ', scoreboard_array.sum() / scoreboard_array.size) 118コード

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

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

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

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

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

xail2222

2021/03/20 00:27

ActivationFunction.pyは作ったんですか?
退会済みユーザー

退会済みユーザー

2021/03/20 00:51

作ってdriveにupしたのですが、これ、googledriveにある他のpythonファイルを呼び出すにはどうすればいいんでしょうか・・・? ひとまず頭に from google.colab import drive drive.mount('/content/drive') をつけたのですが、importできてない・・・。
meg_

2021/03/20 01:19

・パスは'/content/drive/My Drive/colab/ActivationFunction.py'ってことですか? ・質問のタイトルは質問内容が分かるものにしてください。
quickquip

2021/03/20 01:24

自分がやった事を書きましょう。「あなたが参考にしたページ」は回答者があなたの問題を解決する手助けにはあまりなりません。 あと、情報はこの欄ではなく質問を編集して質問に載せましょう。
meg_

2021/03/20 01:35

> ここを参考に、そのまま書きました、そのままなので間違ってると思います。 間違っているか合っているかはご自身しか分からないでしょう。 ActivationFunction.pyはgoogledriveの何処に保存されているんでしょうか?googlecolab上でActivationFunction.pyへのフルパスを確認しましょう。
退会済みユーザー

退会済みユーザー

2021/03/20 02:18 編集

ActivationFunction.pyは、以前、画像をUPした時と同様にアップロードしたため、その時と同様に、 /content/drive にあるはずです、 パスというのがよく分からないのですが、パスはどうかけば良いのでしょうか。
quickquip

2021/03/20 02:02 編集

「以前と同様に」が他人に伝わるように今の状況を質問に書きましょう ActivationFunctionですか? と聞かれてなぜ、Active.pyは〜と答えてるんでしょう?
guest

回答1

0

ベストアンサー

調べた結果を記載します。

Google ColaboratoryでGoogle Drive上の.pyファイルをインポート

ここに

python

1import sys 2sys.path.append('/content/drive/My Drive/Colab/my_project/my_modules')

と書けばよいと書いてあり「Google Drive上の見かけと実際のディレクトリの構造が違う」と書いてありました。

で、実際のディレクトリ構造をどうなってるかを調べないといけないわけですが

python

1import os 2for folder, subfolders, files in os.walk('/content/drive'): 3 print('folder: {}'.format(folder)) 4 print('subfolders: {}'.format(subfolders)) 5 print('files: {}'.format(files)) 6 print()

を実行してみてください。
すると/content/drive配下の構造がわかるかと思います。
これでActivationFunction.pyのある場所がわかると思うので
そのパスに対してsys.path.append()を実行すればインポートできると思います。

簡単なサンプルで私も確認してみましたが出来ました。

投稿2021/03/20 03:17

xail2222

総合スコア1497

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

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

退会済みユーザー

退会済みユーザー

2021/03/20 07:34

Mounted at /content/drive folder: /content/drive subfolders: ['.file-revisions-by-id', '.shortcut-targets-by-id', 'MyDrive', '.Trash'] files: [] folder: /content/drive/.file-revisions-by-id subfolders: [] files: [] folder: /content/drive/.shortcut-targets-by-id subfolders: [] files: [] folder: /content/drive/MyDrive subfolders: ['Colab Notebooks'] files: ['0.png', '1.png', '2.png', '3.png', '4.png', '5.png', '6.png', '7.png', '8.png', '9.png', '3h.png', '2h.png', 'ActivationFunction.py'] folder: /content/drive/MyDrive/Colab Notebooks subfolders: [] files: ['ActivationFunction.py'] folder: /content/drive/.Trash subfolders: [] files: []
xail2222

2021/03/20 07:41

であれば sys.path.append('/content/drive/My Drive/colab') の箇所を sys.path.append('/content/drive/MyDrive’) もしくは sys.path.append('/content/drive/MyDrive/Colab Notebooks') に修正ですね。 どちらが正しいのかわからないですが Googleドライブをみてフォルダ階層的に上側の方と下の方があると思いますが 上側が正しければ一つ目、下側が正しければ二つ目になるんじゃないでしょうか。
退会済みユーザー

退会済みユーザー

2021/03/20 07:47

はい、できました!
退会済みユーザー

退会済みユーザー

2021/03/20 07:48

質問にも追記しましたが、完成コードです、皆さん使ってみて下さい。 import sys from google.colab import drive drive.mount('/content/drive') sys.path.append('/content/drive/My Drive') import numpy as np import ActivationFunction as AF # 3層ニューラルネットワーク class ThreeLayerNetwork: # コンストラクタ def __init__(self, inodes, hnodes, onodes, lr): # 各レイヤーのノード数 self.inodes = inodes self.hnodes = hnodes self.onodes = onodes # 学習率 self.lr = lr # 重みの初期化 self.w_ih = np.random.normal(0.0, 1.0, (self.hnodes, self.inodes)) self.w_ho = np.random.normal(0.0, 1.0, (self.onodes, self.hnodes)) # 活性化関数 self.af = AF.sigmoid self.daf = AF.derivative_sigmoid # 誤差逆伝搬 def backprop(self, idata, tdata): # 縦ベクトルに変換 o_i = np.array(idata, ndmin=2).T t = np.array(tdata, ndmin=2).T # 隠れ層 x_h = np.dot(self.w_ih, o_i) o_h = self.af(x_h) # 出力層 x_o = np.dot(self.w_ho, o_h) o_o = self.af(x_o) # 誤差計算 e_o = (t - o_o) e_h = np.dot(self.w_ho.T, e_o) # 重みの更新 self.w_ho += self.lr * np.dot((e_o * self.daf(o_o)), o_h.T) self.w_ih += self.lr * np.dot((e_h * self.daf(o_h)), o_i.T) # 順伝搬 def feedforward(self, idata): # 入力のリストを縦ベクトルに変換 o_i = np.array(idata, ndmin=2).T # 隠れ層 x_h = np.dot(self.w_ih, o_i) o_h = self.af(x_h) # 出力層 x_o = np.dot(self.w_ho, o_h) o_o = self.af(x_o) return o_o if __name__=='__main__': # パラメータ inodes = 784 hnodes = 100 onodes = 10 lr = 0.3 # ニューラルネットワークの初期化 nn = ThreeLayerNetwork(inodes, hnodes, onodes, lr) # トレーニングデータのロード training_data_file = open('drive/My Drive/mnist_dataset/mnist_train.csv', 'r') training_data_list = training_data_file.readlines() training_data_file.close() # テストデータのロード test_data_file = open('drive/My Drive/mnist_dataset/mnist_test.csv') test_data_list = test_data_file.readlines() test_data_file.close() # 学習 epoch = 10 for e in range(epoch): print('#epoch ', e) data_size = len(training_data_list) for i in range(data_size): if i % 1000 == 0: print(' train: {0:>5d} / {1:>5d}'.format(i, data_size)) val = training_data_list[i].split(',') idata = (np.asfarray(val[1:]) / 255.0 * 0.99) + 0.01 tdata = np.zeros(onodes) + 0.01 tdata[int(val[0])] = 0.99 nn.backprop(idata, tdata) pass pass # テスト scoreboard = [] for record in test_data_list: val = record.split(',') idata = (np.asfarray(val[1:]) / 255.0 * 0.99) + 0.01 tlabel = int(val[0]) predict = nn.feedforward(idata) plabel = np.argmax(predict) scoreboard.append(tlabel == plabel) pass scoreboard_array = np.asarray(scoreboard) print('performance: ', scoreboard_array.sum() / scoreboard_array.size)
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問