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

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

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

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

Q&A

1回答

976閲覧

numba使用時に発生する「TypeError: cannot infer type for global value %r」の解決方法

banquet_kuma

総合スコア18

Python 3.x

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

0グッド

0クリップ

投稿2020/05/26 05:00

前提・実現したいこと

Pythonの実行速度を上げるためにnumbaの使用を検討しています。
しかしながら、TypeErrorが発生し、解決できません。
助言をいただければ幸いです。

よろしくお願いいたします。

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

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-42-350fd3bdbed4> in <module>() 40 P = np.random.rand(N,K) 41 Q = np.random.rand(M,K) ---> 42 nP, nQ = matrix_factorization(R, P, Q, K) 13 frames /usr/local/lib/python3.6/dist-packages/numba/dispatcher.py in _compile_for_args(self, *args, **kws) 418 e.patch_message('\n'.join((str(e).rstrip(), help_msg))) 419 # ignore the FULL_TRACEBACKS config, this needs reporting! --> 420 raise e 421 422 def inspect_llvm(self, signature=None): /usr/local/lib/python3.6/dist-packages/numba/dispatcher.py in _compile_for_args(self, *args, **kws) 351 argtypes.append(self.typeof_pyval(a)) 352 try: --> 353 return self.compile(tuple(argtypes)) 354 except errors.ForceLiteralArg as e: 355 # Received request for compiler re-entry with the list of arguments /usr/local/lib/python3.6/dist-packages/numba/compiler_lock.py in _acquire_compile_lock(*args, **kwargs) 30 def _acquire_compile_lock(*args, **kwargs): 31 with self: ---> 32 return func(*args, **kwargs) 33 return _acquire_compile_lock 34 /usr/local/lib/python3.6/dist-packages/numba/dispatcher.py in compile(self, sig) 766 self._cache_misses[sig] += 1 767 try: --> 768 cres = self._compiler.compile(args, return_type) 769 except errors.ForceLiteralArg as e: 770 def folded(args, kws): /usr/local/lib/python3.6/dist-packages/numba/dispatcher.py in compile(self, args, return_type) 75 76 def compile(self, args, return_type): ---> 77 status, retval = self._compile_cached(args, return_type) 78 if status: 79 return retval /usr/local/lib/python3.6/dist-packages/numba/dispatcher.py in _compile_cached(self, args, return_type) 89 90 try: ---> 91 retval = self._compile_core(args, return_type) 92 except errors.TypingError as e: 93 self._failed_cache[key] = e /usr/local/lib/python3.6/dist-packages/numba/dispatcher.py in _compile_core(self, args, return_type) 107 args=args, return_type=return_type, 108 flags=flags, locals=self.locals, --> 109 pipeline_class=self.pipeline_class) 110 # Check typing error if object mode is used 111 if cres.typing_error is not None and not flags.enable_pyobject: /usr/local/lib/python3.6/dist-packages/numba/compiler.py in compile_extra(typingctx, targetctx, func, args, return_type, flags, locals, library, pipeline_class) 548 """ 549 pipeline = pipeline_class(typingctx, targetctx, library, --> 550 args, return_type, flags, locals) 551 return pipeline.compile_extra(func) 552 /usr/local/lib/python3.6/dist-packages/numba/compiler.py in __init__(self, typingctx, targetctx, library, args, return_type, flags, locals) 278 # Make sure the environment is reloaded 279 config.reload_config() --> 280 typingctx.refresh() 281 targetctx.refresh() 282 /usr/local/lib/python3.6/dist-packages/numba/typing/context.py in refresh(self) 156 Useful for third-party extensions. 157 """ --> 158 self.load_additional_registries() 159 # Some extensions may have augmented the builtin registry 160 self._load_builtins() /usr/local/lib/python3.6/dist-packages/numba/typing/context.py in load_additional_registries(self) 681 682 def load_additional_registries(self): --> 683 from . import ( 684 cffi_utils, 685 cmathdecl, /usr/local/lib/python3.6/dist-packages/numba/typing/randomdecl.py in <module>() 146 @infer_global(random.seed, typing_key="random.seed") 147 @infer_global(np.random.seed, typing_key="np.random.seed") --> 148 class Random_seed(ConcreteTemplate): 149 cases = [signature(types.void, types.uint32)] 150 /usr/local/lib/python3.6/dist-packages/numba/typing/templates.py in decorator(cls) 943 944 def decorator(cls): --> 945 return decorate(cls, typing_key) 946 return decorator 947 /usr/local/lib/python3.6/dist-packages/numba/typing/templates.py in decorate(cls, typing_key) 926 typ = types.Function(Template) 927 else: --> 928 raise TypeError("cannot infer type for global value %r") 929 self.globals.append((val, typ)) 930 return cls TypeError: cannot infer type for global value %r

該当のソースコード

Python

1import numpy as np 2from numba import jit 3 4@jit(nopython=True) 5def matrix_factorization(R, P, Q, K, maxsteps=1000, threshold=0.001,alpha=0.0002, beta=0.02): 6 for step in range(maxsteps): 7 for i in range(len(R)): 8 for j in range(len(R[i])): 9 if R[i][j] > 0: 10 eij = R[i][j] - np.dot(P[i,:],Q[:,j]) 11 for k in range(K): 12 # 勾配法による更新 13 delta_p = alpha * (2 * eij * Q[k][j] - beta * P[i][k]) 14 delta_q = alpha * (2 * eij * P[i][k] - beta * Q[k][j]) 15 P[i][k] += delta_p 16 Q[k][j] += delta_q 17 #RとPQの誤差を更新する 18 e = 0 19 for i in range(len(R)): 20 for j in range(len(R[i])): 21 if R[i][j] > 0: 22 e = e + pow(R[i][j] - np.dot(P[i,:],Q[:,j]), 2) 23 for k in range(K): 24 e = e + (beta/2) * (pow(P[i][k],2) + pow(Q[k][j],2)) 25 # error_list.append(e) 26 if e < threshold: 27 break 28 return P, Q, e 29 30R = [ 31 [5,3,0,1], 32 [4,0,0,1], 33 [1,1,0,5], 34 [1,0,0,4], 35 [0,1,5,4], 36 ] 37 38R = np.array(R) 39 40N = len(R) 41M = len(R[0]) 42K = 2 43P = np.random.rand(N,K) 44Q = np.random.rand(M,K) 45nP, nQ, e = matrix_factorization(R, P, Q, K) 46

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

Google Colabで実施しました。
numpy 1.18.4
numba 0.48.0

試したこと

ローカル環境下でJupyter Labを使って実施してみましたが、
同じエラーが発生しました。

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

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

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

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

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

kabayan55

2020/06/10 11:41

こちらのコード、手元で動かしてみたのですが、別のエラーが出ました。 ValueError: incompatible array sizes for np.dot(a, b) (vector * vector) エラーを再現できないと検証できないので、同じエラーが出る状態になっているか確かめた上でコードを質問に載せていただきたいです。おそらくRの部分かどこかを実際のデータを載せられないために、エラーが出た時から変更しているのかなとは思いました。 "cannot infer type for global value" ですが、numbda は、グローバル変数をサポートしていません。その辺りのエラーだとは思うのですが、検証してみないと回答できません。
banquet_kuma

2020/06/15 11:04

ご指摘ありがとうございます。確認いたします。
banquet_kuma

2020/06/15 12:53 編集

申し訳ありませんでした。 下から2行目の記載が間違っておりました。 誤)Q = np.random.rand(M,K) 正)Q = np.random.rand(K,M) 自己解決欄に追記いたしました。
guest

回答1

0

以下が修正したコードです。問題無く動作しました。
ValueError: incompatible array sizes for np.dot(a, b) (vector * vector)
が出た理由は上記のミスのせいと思われます。
TypeError: cannot infer type for global value %r が出た理由は分かりません。
現在再現もできていない状態です。申し訳ありません。

import numpy as np from numba import jit @jit(nopython=True) def matrix_factorization(R, P, Q, K, maxsteps=1000, threshold=0.001,alpha=0.0002, beta=0.02): for step in range(maxsteps): for i in range(len(R)): for j in range(len(R[i])): if R[i][j] > 0: eij = R[i][j] - np.dot(P[i,:],Q[:,j]) for k in range(K): # 勾配法による更新 delta_p = alpha * (2 * eij * Q[k][j] - beta * P[i][k]) delta_q = alpha * (2 * eij * P[i][k] - beta * Q[k][j]) P[i][k] += delta_p Q[k][j] += delta_q #RとPQの誤差を更新する e = 0 for i in range(len(R)): for j in range(len(R[i])): if R[i][j] > 0: e = e + pow(R[i][j] - np.dot(P[i,:],Q[:,j]), 2) for k in range(K): e = e + (beta/2) * (pow(P[i][k],2) + pow(Q[k][j],2)) # error_list.append(e) if e < threshold: break return P, Q, e R = [ [5,3,0,1], [4,0,0,1], [1,1,0,5], [1,0,0,4], [0,1,5,4], ] R = np.array(R) N = len(R) M = len(R[0]) K = 2 P = np.random.rand(N,K) Q = np.random.rand(K,M) nP, nQ, e = matrix_factorization(R, P, Q, K)

投稿2020/06/15 12:53

banquet_kuma

総合スコア18

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

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

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

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

ただいまの回答率
85.47%

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

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

質問する

関連した質問