當前位置: 首頁>>代碼示例>>Python>>正文


Python computational_graph.build_computational_graph方法代碼示例

本文整理匯總了Python中chainer.computational_graph.build_computational_graph方法的典型用法代碼示例。如果您正苦於以下問題:Python computational_graph.build_computational_graph方法的具體用法?Python computational_graph.build_computational_graph怎麽用?Python computational_graph.build_computational_graph使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在chainer.computational_graph的用法示例。


在下文中一共展示了computational_graph.build_computational_graph方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test(self, cgp, model_file, comp_graph='comp_graph.dot', batchsize=256):
        chainer.cuda.get_device(0).use()  # Make a specified GPU current
        model = CGP2CNN(cgp, self.n_class)
        print('\tLoad model from', model_file)
        serializers.load_npz(model_file, model)
        model.to_gpu(0)
        test_accuracy, test_loss = self.__test(model, batchsize)
        print('\tparamNum={}'.format(model.param_num))
        print('\ttest mean loss={}, test accuracy={}'.format(test_loss / self.test_data_num, test_accuracy / self.test_data_num))

        if comp_graph is not None:
            with open(comp_graph, 'w') as o:
                g = computational_graph.build_computational_graph((model.loss,))
                o.write(g.dump())
                del g
                print('\tCNN graph generated ({}).'.format(comp_graph))

        return test_accuracy, test_loss 
開發者ID:sg-nm,項目名稱:cgp-cnn,代碼行數:20,代碼來源:cnn_train.py

示例2: __call__

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def __call__(self, trainer):
        try:
            var = trainer.observation[self._root_name]
            if not isinstance(var, variable.Variable):
                raise TypeError('root value is not a Variable')
            cg = computational_graph.build_computational_graph(
                [var],
                variable_style=self._variable_style,
                function_style=self._function_style
            ).dump()

            filename = os.path.join(trainer.out, self._filename)
            with open(filename, 'w') as f:
                f.write(cg)
            if is_graphviz_available():
                img_fn = os.path.splitext(self._filename)[0] + '.png'
                image_filename = os.path.join(trainer.out, img_fn)
                subprocess.check_call(
                    ['dot', '-Tpng', filename, '-o', image_filename])
        finally:
            configuration.config.keep_graph_on_report = self._original_flag 
開發者ID:chainer,項目名稱:chainer,代碼行數:23,代碼來源:computational_graph.py

示例3: test_save_normal_graphs

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test_save_normal_graphs(self):
        x = np.random.uniform(-1, 1, self.x_shape)
        x = Variable(x.astype(np.float32))

        for depth in six.moves.range(1, self.n_encdec + 1):
            model = segnet.SegNet(
                n_encdec=self.n_encdec, in_channel=self.x_shape[1])
            y = model(x, depth)
            cg = build_computational_graph(
                [y],
                variable_style=_var_style,
                function_style=_func_style
            ).dump()
            for e in range(1, self.n_encdec + 1):
                self.assertTrue('encdec{}'.format(e) in model._children)

            fn = 'tests/SegNet_x_depth-{}_{}.dot'.format(self.n_encdec, depth)
            if os.path.exists(fn):
                continue
            with open(fn, 'w') as f:
                f.write(cg)
            subprocess.call(
                'dot -Tpng {} -o {}'.format(
                    fn, fn.replace('.dot', '.png')), shell=True) 
開發者ID:pfnet-research,項目名稱:chainer-segnet,代碼行數:26,代碼來源:test_segnet.py

示例4: example_complexity

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def example_complexity(ex):
    return sent_complexity(ex[0]) + sent_complexity(ex[1])



# def write_encdec_loss_computation_graph(encdec, dest_file):
#     batch = [
#         ([0,1,2], [3,5,6,7]),
#         ([0, 0, 0,1,1], [6]),
#         ([5], [2,3,0])
#         ]
#     
#     src_batch, tgt_batch, src_mask = make_batch_src_tgt(batch, eos_idx=8, padding_idx=0, gpu=gpu, volatile="off", need_arg_sort=False)
# 
#     (total_loss, total_nb_predictions), attn = encdec(src_batch, tgt_batch, src_mask, raw_loss_info=True,
#                                                           noise_on_prev_word=noise_on_prev_word,
#                                                           use_previous_prediction=use_previous_prediction,
#                                                           mode="train",
#                                                           use_soft_prediction_feedback=use_soft_prediction_feedback, 
#                                                           use_gumbel_for_soft_predictions=use_gumbel_for_soft_predictions,
#                                                           temperature_for_soft_predictions=temperature_for_soft_predictions)
#     loss = total_loss / total_nb_predictions
#     
#     import chainer.computational_graph as c
#     g = c.build_computational_graph([loss])
#     with open(dest_file, 'w') as o:
#         o.write(g.dump()) 
開發者ID:fabiencro,項目名稱:knmt,代碼行數:29,代碼來源:training_chainer.py

示例5: _check

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def _check(self, outputs, node_num, edge_num):
    g = c.build_computational_graph(outputs)
    self.assertEqual(len(g.nodes), node_num)
    self.assertEqual(len(g.edges), edge_num) 
開發者ID:chainer,項目名稱:chainer,代碼行數:6,代碼來源:test_computational_graph.py

示例6: test_raise_array_outputs

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test_raise_array_outputs(self):
        with self.assertRaises(TypeError):
            c.build_computational_graph(self.z.array) 
開發者ID:chainer,項目名稱:chainer,代碼行數:5,代碼來源:test_computational_graph.py

示例7: setUp

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def setUp(self):
        self.x = variable.Variable(np.zeros((1, 2)).astype(np.float32))
        self.y = 2 * self.x
        self.f = self.y.creator_node
        self.g = c.build_computational_graph((self.y,)) 
開發者ID:chainer,項目名稱:chainer,代碼行數:7,代碼來源:test_computational_graph.py

示例8: test_dont_show_name

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test_dont_show_name(self):
        g = c.build_computational_graph(
            (self.x1, self.x2, self.y), show_name=False)
        dotfile_content = g.dump()
        for var in [self.x1, self.x2, self.y]:
            self.assertNotIn('label="%s:' % var.name, dotfile_content) 
開發者ID:chainer,項目名稱:chainer,代碼行數:8,代碼來源:test_computational_graph.py

示例9: test_randir

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test_randir(self):
        for rankdir in ['TB', 'BT', 'LR', 'RL']:
            g = c.build_computational_graph((self.y,), rankdir=rankdir)
            self.assertIn('rankdir=%s' % rankdir, g.dump()) 
開發者ID:chainer,項目名稱:chainer,代碼行數:6,代碼來源:test_computational_graph.py

示例10: test_randir_invalid

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test_randir_invalid(self):
        self.assertRaises(ValueError,
                          c.build_computational_graph, (self.y,), rankdir='TL') 
開發者ID:chainer,項目名稱:chainer,代碼行數:5,代碼來源:test_computational_graph.py

示例11: dump_comp_graph

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def dump_comp_graph(filename, vs):
    g = C.build_computational_graph(vs)
    with open(filename, 'w') as o:
        o.write(g.dump()) 
開發者ID:orenmel,項目名稱:context2vec,代碼行數:6,代碼來源:train_context2vec.py

示例12: train_loop

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def train_loop():
    # Trainer
    graph_generated = False
    while True:
        while data_q.empty():
            time.sleep(0.1)
        inp = data_q.get()
        if inp == 'end':  # quit
            res_q.put('end')
            break
        elif inp == 'train':  # restart training
            res_q.put('train')
            model.train = True
            continue
        elif inp == 'val':  # start validation
            res_q.put('val')
            serializers.save_npz(args.out, model)
            serializers.save_npz(args.outstate, optimizer)
            model.train = False
            continue

        volatile = 'off' if model.train else 'on'
        x = chainer.Variable(xp.asarray(inp[0]), volatile=volatile)
        t = chainer.Variable(xp.asarray(inp[1]), volatile=volatile)

        if model.train:
            optimizer.update(model, x, t)
            if not graph_generated:
                with open('graph.dot', 'w') as o:
                    o.write(computational_graph.build_computational_graph(
                        (model.loss,)).dump())
                print('generated graph', file=sys.stderr)
                graph_generated = True
        else:
            model(x, t)

        res_q.put((float(model.loss.data), float(model.accuracy.data)))
        del x, t

# Invoke threads 
開發者ID:masataka46,項目名稱:MultimodalDL,代碼行數:42,代碼來源:train_rgb.py

示例13: test_save_loss_graphs_no_class_weight

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def test_save_loss_graphs_no_class_weight(self):
        x = np.random.uniform(-1, 1, self.x_shape)
        x = Variable(x.astype(np.float32))
        t = np.random.randint(
            0, 12, (self.x_shape[0], self.x_shape[2], self.x_shape[3]))
        t = Variable(t.astype(np.int32))

        for depth in six.moves.range(1, self.n_encdec + 1):
            model = segnet.SegNet(n_encdec=self.n_encdec, n_classes=12,
                                  in_channel=self.x_shape[1])
            model = segnet.SegNetLoss(
                model, class_weight=None, train_depth=depth)
            y = model(x, t)
            cg = build_computational_graph(
                [y],
                variable_style=_var_style,
                function_style=_func_style
            ).dump()
            for e in range(1, self.n_encdec + 1):
                self.assertTrue(
                    'encdec{}'.format(e) in model.predictor._children)

            fn = 'tests/SegNet_xt_depth-{}_{}.dot'.format(self.n_encdec, depth)
            if os.path.exists(fn):
                continue
            with open(fn, 'w') as f:
                f.write(cg)
            subprocess.call(
                'dot -Tpng {} -o {}'.format(
                    fn, fn.replace('.dot', '.png')), shell=True) 
開發者ID:pfnet-research,項目名稱:chainer-segnet,代碼行數:32,代碼來源:test_segnet.py

示例14: backprop

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def backprop(self,t,distill=False):
		x=Tensor.context



		self.optimizer.zero_grads()
		if distill:
			loss = self.func.getLossDistill(x.content,t.content)
			accuracy = 0.0
		else:
			loss,accuracy = self.func.getLoss(x.content,t.content)
			accuracy = accuracy.data

		loss.backward()
		self.optimizer.update()
		

		if not self.graph_generated:
			#with open('graph.dot', 'w') as o:
			#	o.write(c.build_computational_graph((loss,), False).dump())
			with open('graph.wo_split.dot', 'w') as o:
				o.write(c.build_computational_graph((loss,), True).dump())
			print('generated graph')
			self.graph_generated = True


		return loss.data,accuracy 
開發者ID:uei,項目名稱:deel,代碼行數:29,代碼來源:nin.py

示例15: backprop

# 需要導入模塊: from chainer import computational_graph [as 別名]
# 或者: from chainer.computational_graph import build_computational_graph [as 別名]
def backprop(self,t,distill=False):
		x=Tensor.context



		self.optimizer.zero_grads()
		if distill:
			t = chainer.Variable(Deel.xp.asarray([t.content.data],dtype=Deel.xp.float32), volatile='off')
			loss = self.func.getLossDistill(x.content,t)
			accuracy = 0.0
		else:
			loss,accuracy = self.func.getLoss(x.content,t.content)
			accuracy = accuracy.data

		loss.backward()
		self.optimizer.update()
		

		if not self.graph_generated:
			#with open('graph.dot', 'w') as o:
			#	o.write(c.build_computational_graph((loss,), False).dump())
			with open('graph.wo_split.dot', 'w') as o:
				o.write(c.build_computational_graph((loss,), True).dump())
			print('generated graph')
			self.graph_generated = True


		return loss.data,accuracy 
開發者ID:uei,項目名稱:deel,代碼行數:30,代碼來源:rnin.py


注:本文中的chainer.computational_graph.build_computational_graph方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。