文書の過去の版を表示しています。
markovchain
markovchainパッケージは、離散状態離散時間マルコフ過程(通称は離散マルコフ過程、あるいはマルコフ連鎖)をRで扱うのに便利な機能を提供する。以下の説明は、https://cran.r-project.org/web/packages/markovchain/vignettes/an_introduction_to_markovchain_package.pdfに基づいている。
マルコフ解析
マルコフ過程に基づいて現象の性質を明らかにしたり、未来の時点のおける状態の確率分布を推定することなどを、マルコフ解析という。
マルコフ解析に必要なもの
マルコフ解析に必要なものは、現在の状態もしくは初期の状態と、対象の状態遷移行列である。
- 状態
- 状態遷移行列
天気の移り変わりを例に説明を進める。
weatherStates <- c("sunny", "cloudy", "rain")
byRow <- TRUE
weatherMatrix <- matrix(data = c(0.70, 0.2, 0.1, 0.3, 0.4, 0.3, 0.2, 0.45, 0.35), byrow = byRow, nrow = 3, dimnames = list(weatherStates, weatherStates))
mcWeather <- new("markovchain", states = weatherStates, byrow = byRow, transitionMatrix = weatherMatrix, name = "Weather")
mcList <- new("markovchainList", markovchains = list(mcWeather, defaultMc), name = "A list of Markov chains")
markovchainのメソッド
Method | Purpose |
* | Direct multiplication for transition matrices. |
[ | Direct access to the elements of the transition matrix. |
== | Equality operator between two transition matrices. |
as | Operator to convert markovchain objects into data.frame and table object. |
dim | Dimension of the transition matrix. |
names | Equal to states. |
names← | Change the states name. |
name | Get the name of markovchain object. |
name← | Change the name of markovchain object. |
plot | plot method for markovchain objects. |
print method for markovchain objects. | |
show | show method for markovchain objects. |
sort | sort method for markovchain objects. |
states | Name of the transition states. |
t | Transposition operator (which switches byrow slot value and modifies the transition matrix coherently). |
markovchainの使い方の基本
上で定義したマルコフ連鎖を確認しておく。
weatherStates weatherMatrix mcWeather
さて、初期状態は曇りcloudy。
initialState = c(0, 1, 0)
二日後の天気の確率分布を求めてみる。
after2Days <- initialState * (mcWeather * mcWeather)
求めた確率分布を確認する。
after2Days
7日後の天気の条件付き確率分布を推定する。
after7Days <- initialState * (mcWeather ^ 7)
求めた確率分布を確認する。
after7Days
こんなに長い桁は必要ないので、四捨五入して小数点以下第3位まで表示してみる。
round(after7Days, 3)
状態を列ベクトルで表すなら、すべてを転地すればいい。
initialState <- c(0, 1, 0) after2Days <- (t(mcWeather) * t(mcWeather)) * initialState after7Days <- (t(mcWeather) ^ 7) * initialState after2Days