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

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

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

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

Python

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

Q&A

解決済

1回答

2739閲覧

状態空間モデルを用いて時系列分析をしたいが、ValueErrorが返ってくる。

Pablito

総合スコア71

Python 3.x

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

Python

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

0グッド

0クリップ

投稿2020/02/20 07:46

編集2020/02/20 08:12

前提・実現したいこと

状態空間モデルを用いて時系列分析をしたいと考えています。

今、ローカルレベルモデルの推定→最尤法によるパラメーラー推定を
行おうとしているのですが、
以下のエラーが返ってきました。

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

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-10-d64133e2c242> in <module> 1 #ローカルモデルの推定 ----> 2 mod_local_level = sm.tsa.UnobservedComponents(guests, 'local level') 3 4 #最尤法によるパラメーターの推定 5 res_local_level = mod_local_level.fit() c:\users\lib\site-packages\statsmodels\tsa\statespace\structural.py in __init__(self, endog, level, trend, seasonal, freq_seasonal, cycle, autoregressive, exog, irregular, stochastic_level, stochastic_trend, stochastic_seasonal, stochastic_freq_seasonal, stochastic_cycle, damped_cycle, cycle_period_bounds, mle_regression, use_exact_diffuse, **kwargs) 571 # Setup the representation 572 super(UnobservedComponents, self).__init__( --> 573 endog, k_states, k_posdef=k_posdef, exog=exog, **kwargs 574 ) 575 self.setup() c:\users\lib\site-packages\statsmodels\tsa\statespace\mlemodel.py in __init__(self, endog, k_states, exog, dates, freq, **kwargs) 136 super(MLEModel, self).__init__(endog=endog, exog=exog, 137 dates=dates, freq=freq, --> 138 missing='none') 139 140 # Store kwargs to recreate model c:\users\lib\site-packages\statsmodels\tsa\base\tsa_model.py in __init__(self, endog, exog, dates, freq, missing, **kwargs) 45 missing='none', **kwargs): 46 super(TimeSeriesModel, self).__init__(endog, exog, missing=missing, ---> 47 **kwargs) 48 49 # Date handling in indexes c:\users\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 234 235 def __init__(self, endog, exog=None, **kwargs): --> 236 super(LikelihoodModel, self).__init__(endog, exog, **kwargs) 237 self.initialize() 238 c:\users\lib\site-packages\statsmodels\base\model.py in __init__(self, endog, exog, **kwargs) 75 hasconst = kwargs.pop('hasconst', None) 76 self.data = self._handle_data(endog, exog, missing, hasconst, ---> 77 **kwargs) 78 self.k_constant = self.data.k_constant 79 self.exog = self.data.exog c:\users\lib\site-packages\statsmodels\base\model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs) 98 99 def _handle_data(self, endog, exog, missing, hasconst, **kwargs): --> 100 data = handle_data(endog, exog, missing, hasconst, **kwargs) 101 # kwargs arrays could have changed, easier to just attach here 102 for key in kwargs: c:\users\lib\site-packages\statsmodels\base\data.py in handle_data(endog, exog, missing, hasconst, **kwargs) 670 klass = handle_data_class_factory(endog, exog) 671 return klass(endog, exog=exog, missing=missing, hasconst=hasconst, --> 672 **kwargs) c:\users\lib\site-packages\statsmodels\base\data.py in __init__(self, endog, exog, missing, hasconst, **kwargs) 81 self.orig_endog = endog 82 self.orig_exog = exog ---> 83 self.endog, self.exog = self._convert_endog_exog(endog, exog) 84 85 self.const_idx = None c:\users\lib\site-packages\statsmodels\base\data.py in _convert_endog_exog(self, endog, exog) 506 exog = exog if exog is None else np.asarray(exog) 507 if endog.dtype == object or exog is not None and exog.dtype == object: --> 508 raise ValueError("Pandas data cast to numpy dtype of object. " 509 "Check input data with np.asarray(data).") 510 return super(PandasData, self)._convert_endog_exog(endog, exog) ValueError: Pandas data cast to numpy dtype of object. Check input data with np.asarray(data).

データの中身は下のような感じです。

date guests 0 2020-05-22 3668 1 2020-05-23 4372 2 2020-05-24 4901 3 2020-05-25 5664 4 2020-05-26 4663

該当のソースコード

Python

1#ローカルモデルの推定 2mod_local_level = sm.tsa.UnobservedComponents(guests, 'local level') 3 4#最尤法によるパラメーターの推定 5res_local_level = mod_local_level.fit() 6 7#推定されたパラメーター一覧 8print(res_local_level.summary())

試したこと

元データの’を消してみたり、したのですが効果はなし。
dateがdatetime型なので、
以下のコードでint型にしたところ、違うエラーが返ってきました。

def to_integer(dt_time): return 10000*dt_time.year + 100*dt_time.month + dt_time.day guests['date'] = guests['date'].apply(to_integer)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-12-d64133e2c242> in <module> 3 4 #最尤法によるパラメーターの推定 ----> 5 res_local_level = mod_local_level.fit() 6 7 #推定されたパラメーター一覧 c:\users\lib\site-packages\statsmodels\tsa\statespace\mlemodel.py in fit(self, start_params, transformed, includes_fixed, cov_type, cov_kwds, method, maxiter, full_output, disp, callback, return_params, optim_score, optim_complex_step, optim_hessian, flags, low_memory, **kwargs) 605 """ 606 if start_params is None: --> 607 start_params = self.start_params 608 transformed = True 609 includes_fixed = True c:\users\lib\site-packages\statsmodels\tsa\statespace\structural.py in start_params(self) 846 _start_params = {} 847 if self.level: --> 848 resid, trend1 = hpfilter(endog) 849 850 if self.stochastic_trend: c:\users\lib\site-packages\statsmodels\tsa\filters\hp_filter.py in hpfilter(x, lamb) 88 """ 89 pw = PandasWrapper(x) ---> 90 x = array_like(x, 'x', ndim=1) 91 nobs = len(x) 92 I = sparse.eye(nobs, nobs) # noqa:E741 c:\users\lib\site-packages\statsmodels\tools\validation\validation.py in array_like(obj, name, dtype, ndim, maxdim, shape, order, contiguous, optional) 134 if arr.ndim != ndim: 135 msg = '{0} is required to have ndim {1} but has ndim {2}' --> 136 raise ValueError(msg.format(name, ndim, arr.ndim)) 137 if shape is not None: 138 for actual, req in zip(arr.shape, shape): ValueError: x is required to have ndim 1 but has ndim 2

###環境
pandas 1.0.0
numpy 1.18.1
statsmodels 0.11.0

何卒宜しくお願い致します。

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

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

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

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

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

guest

回答1

0

自己解決

mod_local_level = sm.tsa.UnobservedComponents(guests, 'local level')

mod_local_level = sm.tsa.UnobservedComponents(data['guests'], 'local level')
に変えたら実行できました。

ありがとうございました。

投稿2020/02/20 08:31

Pablito

総合スコア71

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問