2015年12月21日月曜日

[Rの]Andrew先生の機械学習1[練習]

折角Andrew先生の講義を一通り終えたので、復習とRの練習のため、練習問題をRに移植。
matlabに慣れていたのもあって、講義の問題はだいたい2時間以内で終わっていたけれども、Rではもっと時間がかかりそう。最後まで続けられるか微妙。

最初のお題は線形回帰
Rの組み込み関数lmを使った。
plot関数を重ねて使うとあまりよくないらしい。

ex1 <- function()
{
    data = read.csv('ex1data1.txt', header = F)
    X <- data[, 1]
    y <- data[, 2]
    plot(X, y, xlim = c(0.9 * min(X), 1.1 * max(X)), ylim = c(0.9 * min(y), 1.1 * max(y)))
    par(new=T)

    m = length(y) # number of training examples
    fit <- lm(y ~ X)
    theta <- c(coef(fit))
    print(theta)
   
    xx <- c(min(X), max(X))
    yy <- theta[2] * xx + theta[1]
    # if it were not for xlim & ylim the plotted axis is worngly overlapped
    plot(xx, yy, type = 'l', xlim = c(0.9 * min(X), 1.1 * max(X)), ylim = c(0.9 * min(y), 1.1 * max(y)), xlab = "", ylab = "")
}






















bloggerでは手軽にコードを記載する方法が見つからなかった。
はてなではとても簡単にコードを色分けして表示できそうでかっこよかった。

0 件のコメント:

コメントを投稿