Triad sou.

記号微分

deriv を利用して、R で記号微分してみます。

正規分布の対数尤度関数を記号微分してみよう

正規分布の対数尤度関数は、
\[
l(\mu, \s; x)=-\frac{\log(2\pi\s^2)}{2}-\frac{(x - \mu)^2}{2\s^2}
\] ですので、これを偏微分すると、
\[
\begin{align*}
\frac{\partial l(\mu, \s; x)}{\partial \mu} &= \frac{x-\mu}{\s^2} \\
\frac{\partial l(\mu, \s; x)}{\partial \s} &= -\frac{1}{\s}+\frac{(x-\mu)^2}{\s^3}
\end{align*}
\] となる予定です。


deriv を用いた数値微分では、まず被微分関数を expressioncall、または formula の形で定義します。

fx <- expression(
  -log(2*pi*sd^2)/2 - (x - mean)^2/(2*sd^2)
)


あとは、

  • 定義した被微分関数
  • 微分したい変数名
  • 出力される微分された関数に対する引数名
  • 必要に応じてオプション

を指定して実行するだけです。

dfx <- deriv(
  fx,
  c("mean", "sd"),
  function.arg = c("x", "mean", "sd")
)
dfx


結果は以下のようになりました。

> dfx
function (x, mean, sd) 
{
    .expr1 <- 2 * pi
    .expr2 <- sd^2
    .expr3 <- .expr1 * .expr2
    .expr7 <- x - mean
    .expr8 <- .expr7^2
    .expr9 <- 2 * .expr2
    .expr14 <- 2 * sd
    .value <- -log(.expr3)/2 - .expr8/.expr9
    .grad <- array(0, c(length(.value), 2L), list(NULL, c("mean", 
        "sd")))
    .grad[, "mean"] <- 2 * .expr7/.expr9
    .grad[, "sd"] <- -(.expr1 * .expr14/.expr3/2 - .expr8 * (2 * 
        .expr14)/.expr9^2)
    attr(.value, "gradient") <- .grad
    .value
}


一応確認しておくと、

.expr2 <- sd^2
.expr7 <- x - mean
.expr9 <- 2 * .expr2
.grad[, "mean"] <- 2 * .expr7/.expr9

# 2 * .expr7/.expr9 =
#   2 * (x - mean) / 2 * sd^2 =
#   (x - mean) / sd^2

および、

.expr1 <- 2 * pi
.expr2 <- sd^2
.expr3 <- .expr1 * .expr2
.expr7 <- x - mean
.expr8 <- .expr7^2
.expr9 <- 2 * .expr2
.expr14 <- 2 * sd
.grad[, "sd"] <- -(.expr1 * .expr14/.expr3/2 - .expr8 * (2 * 
        .expr14)/.expr9^2)

# -.expr1 * .expr14/.expr3/2 =
#   -2 * pi * 2 * sd / (2 * pi * sd^2) / 2 =
#   -1/sd
# .expr8 * (2 * .expr14)/.expr9^2 =
#   (x - mean)^2 * (2 * 2 * sd) / (2 * sd^2)^2 =
#   (x - mean)^2 / sd^3

となります。
このぐらいなら手計算の方が早いですが、いろいろな場面で利用できるのではないでしょうか。


また、Hessian を自動で出してくれる deriv3 もあります。

注意

deriv のヘルプのタイトルは、

Symbolic and Algorithmic Derivatives of Simple Expressions

となっていて、以下の説明があります。

The internal code knows about the arithmetic operators +, -, *, / and ^, and the single-variable functions exp, log, sin, cos, tan, sinh, cosh, sqrt, pnorm, dnorm, asin, acos, atan, gamma, lgamma, digamma and trigamma, as well as psigamma for one or two arguments (but derivative only with respect to the first). (Note that only the standard normal distribution is considered.)

deriv では基本的な演算子と、いくつかの単変数の関数ぐらいしか使えないため、被微分関数を作るときに注意が必要です。

RcmdrPlugin.KMggplot2_0.1-0 is on CRAN now

I posted a new version of the "RcmdrPlugin.KMggplot2" package, which is an Rcmdr plug-in for a "ggplot2" GUI front-end.
This package assists you to make "ggplot2" graphics.

NEWS

Changes in version 0.1-0 (2012-05-18)
theme_simple()

The theme_simple() is a simple black and white theme.
Top and right borders and both grids are removed from the theme_bw().

A list box for facet_xx() functions

A list box for facet_xx() functions was added.

Confidence intervals for Kaplan-Meier plots

Violin plots

Stacked bar charts

Univariate plots at diagonal positions (ggplot2::plotmatrix)

"..count.. + facet_grid" の挙動について

追記

ggplot-0.9.1 で修正されていました!
ggplot-0.9.1 での実行結果

メモ

スクリプトの書き方が良くないのかもしれませんが、..count..facet_gridを併用したときの挙動をメモっておきます。
バージョンは R-2.15.0 + ggplot-0.9.0 です。


こう書くと全ての度数が 1 になってしまう。

require("ggplot2")

mydf1 <- data.frame(
  x = sample(letters[1:2], 500, replace = T),
  y = sample(letters[10:11], 500, replace = T)
)

ggplot(mydf1, aes(x = x, y = ..count..)) +
  geom_bar() + facet_grid( ~ y) + opts(title = "..count.. + facet_grid")


facet_wrap の場合は意図したグラフが得られました。

ggplot(mydf1, aes(x = x, y = ..count..)) +
  geom_bar() + facet_wrap( ~ y) + opts(title = "..count.. + facet_wrap")


また、データフレームに id 変数を加えてみると facet_wrap の結果と一致しました。

mydf2 <- data.frame(
  mydf1,
  id = 1:500
)
ggplot(mydf2, aes(x = x, y = ..count..)) +
  geom_bar() + facet_grid( ~ y) + opts(title = "..count.. + facet_grid + id"))


何でだろう。
多分 ..count.. の挙動を良く理解していないからだろう。

行列のスカラー微分のメモ

$\mathbf{A}$, $\mathbf{B}$ について、スカラー $\theta$ で微分する場合を考える。
だたし、
\[
\mathbf{A}= \left\{ a_{ij} \right\}, \frac{\partial \mathbf{A}}{\partial \theta}= \left\{ \frac{\partial a_{ij}}{\partial \theta} \right\}
\] とし、$\mathbf{B}$ も同様に定義する。

行列積の微分

行列積 $\mathbf{A} \mathbf{B}$ が定義できる場合、
\[
\frac{\partial \mathbf{A}\mathbf{B}}{\partial \theta}= \frac{\partial \mathbf{A}}{\partial \theta}\mathbf{B} + \mathbf{A}\frac{\partial \mathbf{B}}{\partial \theta}
\]

逆行列微分

$\mathbf{A}$ が正方行列で逆行列が存在するならば、
\[
\frac{\partial \mathbf{A}^{-1}}{\partial \theta}= -\mathbf{A}^{-1} \frac{\partial \mathbf{A}}{\partial \theta} \mathbf{A}^{-1}
\]

逆行列微分の導出

\[
\begin{align*}
\frac{\partial \mathbf{A}\mathbf{A}^{-1}}{\partial \theta} &=
\frac{\partial \mathbf{I}}{\partial \theta} \\
\frac{\partial \mathbf{A}}{\partial \theta}\mathbf{A}^{-1} + \mathbf{A}\frac{\partial \mathbf{A}^{-1}}{\partial \theta} &=
\mathbf{0}\\
\mathbf{A}\frac{\partial \mathbf{A}^{-1}}{\partial \theta} &= -\frac{\partial \mathbf{A}}{\partial \theta}\mathbf{A}^{-1} \\
\frac{\partial \mathbf{A}^{-1}}{\partial \theta} &= -\mathbf{A}^{-1}\frac{\partial \mathbf{A}}{\partial \theta}\mathbf{A}^{-1}
\end{align*}
\]

正方行列 $\mathbf{A}$, $\mathbf{B}$ について、
\[
\begin{align*}
\frac{\partial \mathbf{A}^{-1}\mathbf{B}\mathbf{A}^{-1}}{\partial \theta} &=
\frac{\partial \mathbf{A}^{-1}}{\partial \theta}\mathbf{B}\mathbf{A}^{-1} + \mathbf{A}^{-1}\frac{\partial \mathbf{B}\mathbf{A}^{-1}}{\partial \theta} \\ &= -\mathbf{A}^{-1}\frac{\partial \mathbf{A}}{\partial \theta}\mathbf{A}^{-1}\mathbf{B}\mathbf{A}^{-1} + \mathbf{A}^{-1}\frac{\partial \mathbf{B}}{\partial \theta}\mathbf{A}^{-1} - \mathbf{A}^{-1}\mathbf{B}\mathbf{A}^{-1}\frac{\partial \mathbf{A}}{\partial \theta}\mathbf{A}^{-1} \\ &=
\mathbf{A}^{-1} \left( \frac{\partial \mathbf{B}}{\partial \theta} -\frac{\partial \mathbf{A}}{\partial \theta}\mathbf{A}^{-1}\mathbf{B} -\mathbf{B}\mathbf{A}^{-1}\frac{\partial \mathbf{A}}{\partial \theta} \right) \mathbf{A}^{-1}
\end{align*}
\]

$\mathbf{A}$ の要素が全て定数の場合、$\partial \mathbf{A} / \partial \theta = \mathbf{0}$ より $\mathbf{A}^{-1} (\partial \mathbf{B} / \partial \theta) \mathbf{A}^{-1}$。

ちらつかない JEditorPane クラス の setText メソッド

JEditorPane クラス の setText メソッド

public void setText(String t) {
  try {
    Document doc = getDocument();
    doc.remove(0, doc.getLength());
    if (t == null || t.equals("")) {
      return;
    }
    Reader r = new StringReader(t);
    EditorKit kit = getEditorKit();
    kit.read(r, doc, 0);
  } catch (IOException ioe) {
    UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  } catch (BadLocationException ble) {
    UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
  }
}

のように実装されていて、いったんドキュメントをクリア

    Document doc = getDocument();
    doc.remove(0, doc.getLength());

してから、kit.read(r, doc, 0); する仕様です。


このせいで、Timer 中で回したりしていると、クリアしている部分が見えてしまうことがあって、画面がちらついてしまいます。
というわけで、

class ExtJEdit extends JEditorPane {
  public void setText(String t) {
    if (t == null || t.equals("")) {
      return;
    }
    Reader r = new StringReader(t);
    HTMLDocument doc = new HTMLDocument();
    HTMLEditorKit kit = new HTMLEditorKit();
    try {
      kit.read(r, doc, 0);
      this.setDocument(doc);
    } catch (IOException e) {
      UIManager.getLookAndFeel().provideErrorFeedback(this);
    } catch (BadLocationException e) {
      UIManager.getLookAndFeel().provideErrorFeedback(this);
    }
  }
}

こんな感じに変更してみたところ、ほぼちらつかなくなりました。

サンプル



ちらつかない場合もあるので、適当にボタンを押しまくってください。

New 'ByteCompile' field in the DESCRIPTION file

R 2.14.0 から DESCRIPTION ファイルに 'ByteCompile' フィールドを指定できるようになったらしい。
パッケージ中の R コードを自動的にバイトコンパイルしてくれるため、ものによっては高速化が見込めるという感じ。
試してみようかな。

The `ByteCompile' field controls if the package code is byte-compiled on installation: the default is currently not to, so this may be useful for a package known to benefit particularly from byte-compilation (which can take quite a long time and increases the installed size of the package).

Writing R Extensions / 1.1.1 The DESCRIPTION file

リンク