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

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

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

Chainerは、国産の深層学習フレームワークです。あらゆるニューラルネットワークをPythonで柔軟に書くことができ、学習させることが可能。GPUをサポートしており、複数のGPUを用いた学習も直感的に記述できます。

Python

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

Q&A

解決済

1回答

548閲覧

chainerのサンプルコードの実装

emiime

総合スコア27

Chainer

Chainerは、国産の深層学習フレームワークです。あらゆるニューラルネットワークをPythonで柔軟に書くことができ、学習させることが可能。GPUをサポートしており、複数のGPUを用いた学習も直感的に記述できます。

Python

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

0グッド

0クリップ

投稿2018/12/23 09:31

以下のコードを実装すると、
ImportError: cannot import name 'chainerx'
と出てきてしまいます。
これはchainerのサンプルコードなのですが、
どうして実行できないのかわかりません

教えてください。

python

1#!/usr/bin/env python 2import argparse 3import re 4 5import numpy 6 7import chainer 8import chainer.functions as F 9import chainer.links as L 10from chainer import training 11from chainer.training import extensions 12import chainerx 13 14 15# Network definition 16class MLP(chainer.Chain): 17 18 def __init__(self, n_units, n_out): 19 super(MLP, self).__init__() 20 with self.init_scope(): 21 # the size of the inputs to each layer will be inferred 22 self.l1 = L.Linear(None, n_units) # n_in -> n_units 23 self.l2 = L.Linear(None, n_units) # n_units -> n_units 24 self.l3 = L.Linear(None, n_out) # n_units -> n_out 25 26 def forward(self, x): 27 h1 = F.relu(self.l1(x)) 28 h2 = F.relu(self.l2(h1)) 29 return self.l3(h2) 30 31 32def parse_device(args): 33 gpu = None 34 if args.gpu is not None: 35 gpu = args.gpu 36 elif re.match(r'(-|+|)[0-9]+$', args.device): 37 gpu = int(args.device) 38 39 if gpu is not None: 40 if gpu < 0: 41 return chainer.get_device(numpy) 42 else: 43 import cupy 44 return chainer.get_device((cupy, gpu)) 45 46 return chainer.get_device(args.device) 47 48 49def main(): 50 parser = argparse.ArgumentParser(description='Chainer example: MNIST') 51 parser.add_argument('--batchsize', '-b', type=int, default=100, 52 help='Number of images in each mini-batch') 53 parser.add_argument('--epoch', '-e', type=int, default=20, 54 help='Number of sweeps over the dataset to train') 55 parser.add_argument('--frequency', '-f', type=int, default=-1, 56 help='Frequency of taking a snapshot') 57 parser.add_argument('--device', '-d', type=str, default='-1', 58 help='Device specifier. Either ChainerX device ' 59 'specifier or an integer. If non-negative integer, ' 60 'CuPy arrays with specified device id are used. If ' 61 'negative integer, NumPy arrays are used') 62 parser.add_argument('--out', '-o', default='result', 63 help='Directory to output the result') 64 parser.add_argument('--resume', '-r', default='', 65 help='Resume the training from snapshot') 66 parser.add_argument('--unit', '-u', type=int, default=1000, 67 help='Number of units') 68 parser.add_argument('--noplot', dest='plot', action='store_false', 69 help='Disable PlotReport extension') 70 group = parser.add_argument_group('deprecated arguments') 71 group.add_argument('--gpu', '-g', type=int, nargs='?', const=0, 72 help='GPU ID (negative value indicates CPU)') 73 args = parser.parse_args() 74 75 device = parse_device(args) 76 77 print('Device: {}'.format(device)) 78 print('# unit: {}'.format(args.unit)) 79 print('# Minibatch-size: {}'.format(args.batchsize)) 80 print('# epoch: {}'.format(args.epoch)) 81 print('') 82 83 # Set up a neural network to train 84 # Classifier reports softmax cross entropy loss and accuracy at every 85 # iteration, which will be used by the PrintReport extension below. 86 model = L.Classifier(MLP(args.unit, 10)) 87 model.to_device(device) 88 device.use() 89 90 # Setup an optimizer 91 optimizer = chainer.optimizers.Adam() 92 optimizer.setup(model) 93 94 # Load the MNIST dataset 95 train, test = chainer.datasets.get_mnist() 96 97 train_iter = chainer.iterators.SerialIterator(train, args.batchsize) 98 test_iter = chainer.iterators.SerialIterator(test, args.batchsize, 99 repeat=False, shuffle=False) 100 101 # Set up a trainer 102 updater = training.updaters.StandardUpdater( 103 train_iter, optimizer, device=device) 104 trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out) 105 106 # Evaluate the model with the test dataset for each epoch 107 trainer.extend(extensions.Evaluator(test_iter, model, device=device)) 108 109 # Dump a computational graph from 'loss' variable at the first iteration 110 # The "main" refers to the target link of the "main" optimizer. 111 # TODO(niboshi): Temporarily disabled for chainerx. Fix it. 112 if device.xp is not chainerx: 113 trainer.extend(extensions.dump_graph('main/loss')) 114 115 # Take a snapshot for each specified epoch 116 frequency = args.epoch if args.frequency == -1 else max(1, args.frequency) 117 trainer.extend(extensions.snapshot(), trigger=(frequency, 'epoch')) 118 119 # Write a log of evaluation statistics for each epoch 120 trainer.extend(extensions.LogReport()) 121 122 # Save two plot images to the result dir 123 if args.plot and extensions.PlotReport.available(): 124 trainer.extend( 125 extensions.PlotReport(['main/loss', 'validation/main/loss'], 126 'epoch', file_name='loss.png')) 127 trainer.extend( 128 extensions.PlotReport( 129 ['main/accuracy', 'validation/main/accuracy'], 130 'epoch', file_name='accuracy.png')) 131 132 # Print selected entries of the log to stdout 133 # Here "main" refers to the target link of the "main" optimizer again, and 134 # "validation" refers to the default name of the Evaluator extension. 135 # Entries other than 'epoch' are reported by the Classifier link, called by 136 # either the updater or the evaluator. 137 trainer.extend(extensions.PrintReport( 138 ['epoch', 'main/loss', 'validation/main/loss', 139 'main/accuracy', 'validation/main/accuracy', 'elapsed_time'])) 140 141 # Print a progress bar to stdout 142 trainer.extend(extensions.ProgressBar()) 143 144 if args.resume: 145 # Resume from a snapshot 146 chainer.serializers.load_npz(args.resume, trainer) 147 148 # Run the training 149 trainer.run() 150 151 152if __name__ == '__main__': 153 main() 154

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

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

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

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

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

Q71

2018/12/23 13:40

あなたがインストールしているChainerのバージョンを教えてください。
quickquip

2018/12/23 13:43

どこにあるサンプルコードですか? ChainerXのサンプルをChainerのサンプルだと思ってしまっているだけでは。
guest

回答1

0

ベストアンサー

v5系のコードはimport chainerxはないです。
https://github.com/chainer/chainer/blob/v5/examples/mnist/train_mnist.py


ChainerXがChainer本体にはいるのはv6系からなので、(結果的に)v6用のサンプルをv5で動かしていることになります。
https://github.com/chainer/chainer/releases/tag/v6.0.0b1


サンプルコードをgitで取っているならv5系をチェックアウトするか、v5系のtarファイルをダウンロードして解凍して使うかすればいいでしょう。
https://github.com/chainer/chainer/releases/tag/v5.1.0

投稿2018/12/23 14:47

quickquip

総合スコア11029

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

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

emiime

2018/12/23 15:53

v5系のコードで実装できました。 本当にありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問