Contenu connexe
Similaire à 入門機械学習1,2章 (20)
Plus de Kazufumi Ohkawa (20)
入門機械学習1,2章
- 2. 準備
! R
! http://www.r-project.org/
! Rstudio
! http://www.rstudio.com/
! サンプルコード
! https://github.com/johnmyleswhite/
ML_for_Hackers
! source( package_installer.R )を実行
>
setwd("/Users/kzfm/lang/rcode/ML_̲for_̲Hackers/")
>
source("package_̲installer.R")
- 5. Rとは?
! 統計計算とグラフィックスのための言語・環境
! 多様な統計手法 (線形・非線形モデル、古典的統
計検定、時系列解析、判別分析、クラスタリング、
その他) とグラフィックスを提供し、広汎な拡張
が可能
! オブジェクト指向
! 統計処理用の関数が豊富に用意されている
! ベクトル、行列演算のためのデータ型が存在す
る
- 6. 例)package_installer.R
options(repos=structure(c(CRAN="http://cran.stat.auckland.ac.nz/")))
cran.packages
<-‐‑‒
c("e1071”,
"ggplot2”,
"glmnet",
"Hmisc”,
"igraph”,
"lme4",
"lubridate”,
"plyr”,
"RCurl",
"reshape”,
"RJSONIO",
"scales”,
"tm”,
"XML")
cat("This
script
will
now
attempt
to
install
all
of
the
R
packages
used
in
'Machine
Learning
for
Hackers'")
for(p
in
cran.packages)
{
if(!suppressWarnings(require(p,
character.only
=
TRUE,
quietly
=
TRUE)))
{
cat(paste(p,
"missing,
will
attempt
to
installn"))
install.packages(p,
dependencies
=
TRUE,
type
=
"source")
}
else
{
cat(paste(p,
"installed
OKn"))
}
}
print("###
All
required
packages
installed
###")
代入が<- になったjavascriptだと思えばOK
- 7. javascriptとの違い
! function
! セミコロンは不要
! 引数にデフォルトを与えることができる
! 最後に評価された値が返る
! returnは関数(括弧が必要)
! 集合型の添字が1からはじまる
! ココらへんに気をつければ、Rのコードは読める
と思います
- 9. ベクトル
! 皆さんが想像する通りの
ものです
! c()で生成
! 均質
! 要素の種類は同じでな
いといけない
! インデックス付けできる
! v[1]でアクセスできる
! 名前付けできる
! namesを使う
>
MLer
<-‐‑‒
c("kzfm",
"tomof",
"harumakiyukko")
>
names(MLer)
<-‐‑‒
NULL
>
MLer
[1]
"kzfm"
"tomof"
"harumakiyukko"
>
MLer[2]
[1]
"tomof"
>
names(MLer)
<-‐‑‒
c("user1","user2","user3")
>
MLer
user1
user2
user3
"kzfm"
"tomof"
"harumakiyukko"
- 10. リスト
! 皆さんが想像するものとは
ちがいます
! どっちかというと辞書や
ハッシュ
! list()で生成
! 異質
! 要素の種類は異なってい
て良い
! インデックス付けできる
! v[[1]]でアクセスできる
! 名前付けできる
! lst[[ name ]]の省略記
法としてlst$nameが使
える(javascriptみたい
なもん)
>shizudev
<-‐‑‒
list(title="⼊入⾨門機械学習読書会",
users=MLer)
>
shizudev[[1]]
[1]
"⼊入⾨門機械学習読書会"
>
shizudev[[2]]
user1
user2
user3
"kzfm"
"tomof"
"harumakiyukko"
>
shizudev$title
[1]
"⼊入⾨門機械学習読書会"
>
shizudev$users
user1
user2
user3
"kzfm"
"tomof"
"harumakiyukko"
- 11. ベクトルとリストの違い
! 均質か異質か
! リストがハッシュっぽいのは異質なデータ集合の
添字に名前を付けられるから
1
2
3
4
5
6
lst[[1]] or lst[[ name1 ]] or lst$name1
lst
- 12. ベクトル操作と型変換
! ベクトル操作はこん
な感じ
! 型を調べるのはis
! 型変換はas
! Factor
! 列挙型とかEnum
! SQLだと正規化し
たイメージ
>
v
<-‐‑‒
1:5
>
v
[1]
1
2
3
4
5
>
v
+
5
[1]
6
7
8
9
10
>
v[3]
+
5
[1]
8
>
v[3]
<-‐‑‒
v[3]
+
5
>
v
[1]
1
2
8
4
5
>
v2
<-‐‑‒
1:5
>
v2
+
v2
[1]
2
4
6
8
10
>
v3
<-‐‑‒
c("F","M","F","F")
>
v3
[1]
"F"
"M"
"F"
"F"
>
is.vector(v3)
[1]
TRUE
>
v4
<-‐‑‒
as.factor(v3)
>
v4
[1]
F
M
F
F
Levels:
F
M
- 14. データフレーム
>
langs
<-‐‑‒
read.csv("lang.csv",
header=TRUE)
>
langs
lang
statements
lines
1
C
1.0
1.000
2
C++
2.5
1.000
3
Fortran
2.5
0.800
4
Java
2.5
1.500
5
Perl
6.0
6.000
6
Python
6.0
6.500
7
Smalltalk
6.0
0.625
>
langs[[1]]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
>
langs[1,]
lang
statements
lines
1
C
1
1
>
langs[,1]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
- 15. データフレーム
>
langs
<-‐‑‒
read.csv("lang.csv",
header=TRUE)
>
langs
lang
statements
lines
1
C
1.0
1.000
2
C++
2.5
1.000
3
Fortran
2.5
0.800
4
Java
2.5
1.500
5
Perl
6.0
6.000
6
Python
6.0
6.500
7
Smalltalk
6.0
0.625
>
langs[[1]]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
>
langs[1,]
lang
statements
lines
1
C
1
1
>
langs[,1]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
- 16. データフレーム
>
langs
<-‐‑‒
read.csv("lang.csv",
header=TRUE)
>
langs
lang
statements
lines
1
C
1.0
1.000
2
C++
2.5
1.000
3
Fortran
2.5
0.800
4
Java
2.5
1.500
5
Perl
6.0
6.000
6
Python
6.0
6.500
7
Smalltalk
6.0
0.625
>
langs[[1]]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
>
langs[1,]
lang
statements
lines
1
C
1
1
>
langs[,1]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
- 18. リストの記法でアクセス
>
langs
<-‐‑‒
read.csv("lang.csv",
header=TRUE)
>
langs
lang
statements
lines
1
C
1.0
1.000
2
C++
2.5
1.000
3
Fortran
2.5
0.800
4
Java
2.5
1.500
5
Perl
6.0
6.000
6
Python
6.0
6.500
7
Smalltalk
6.0
0.625
>
langs[[1]]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
>
langs[1,]
lang
statements
lines
1
C
1
1
>
langs[,1]
[1]
C
C++
Fortran
Java
Perl
Python
Smalltalk
Levels:
C
C++
Fortran
Java
Perl
Python
Smalltalk
- 23. CRAN
! perlでいうところのCPAN
! http://cran.r-project.org/
! パッケージが登録されている
! Rstudioの場合
! Tools -> install Packagesでインストール
! 対話環境の場合
! install.packages関数
! パッケージを使う
! library関数 #jsでいうrequire
- 26. データを綺麗にする
setwd("/Users/kzfm/lang/rcode/ML_̲for_̲Hackers/01-‐‑‒Introduction/")
ufo
<-‐‑‒
read.delim("data/ufo/ufo_̲awesome.tsv",
sep="t",
stringsAsFactors=FALSE,
header=FALSE,
na.strings="")
names(ufo)
<-‐‑‒
c("DateOccurred",
"DateReported",
"Location",
"ShortDescription",
"Duration",
"LongDescription")
good.rows
<-‐‑‒
ifelse(nchar(ufo$DateOccurred)
!=8
|
nchar(ufo$DateReported)
!=8,
FALSE,
TRUE)
ufo
<-‐‑‒
ufo[good.rows,]
ufo$DateOccurred
<-‐‑‒
as.Date(ufo$DateOccurred,
format="%Y%m%d")
ufo$DateReported
<-‐‑‒
as.Date(ufo$DateReported,
format="%Y%m%d")
get.location
<-‐‑‒
function(l)
{
split.location
<-‐‑‒
tryCatch(strsplit(l,",")[[1]],
error=
function(e)
return(c(NA,
NA)))
clean.location
<-‐‑‒
gsub("^
",
"",
split.location)
if(length(clean.location)
>
2)
{
return(c(NA,
NA))
}
else
{
return(clean.location)
}
}
city.state
<-‐‑‒
lapply(ufo$Location,
get.location)
location.matrix
<-‐‑‒
do.call(rbind,
city.state)
ufo
<-‐‑‒
transform(ufo,
USCity=location.matrix[,1],
USState=location.matrix[,2],stringsAsFactors=FALSE)
ufo$USState
<-‐‑‒
state.abb[match(ufo$USState,
state.abb)]
ufo$USCity[is.na(ufo$USState)]
<-‐‑‒
NA
ufo.us
<-‐‑‒
subset(ufo,
!is.na(USState))
ML_for_Hackers/01-Introduction/ufo_sightings.R
を参考に
- 27. コードの説明
! TAB区切りのデータ読み込み
! ヘッダを設定
! 日付のフォーマットがおかしい行を捨てる
! 位置情報を綺麗にする
! 目撃された場所がアメリカ(州コード)のもの
のみにする
! (*) 表に対する操作を意識するとより分かりやす
いかも
- 28. lapply, do.call
! jQuery.mapみたいな
! 高階関数を使ってforループ
を回さないのがRの作法
! lapply
! (DataFrame -> list)
! do.call
! (list -> DataFrame) lapply(iris[1:4],
mean)
- 38. 1990-1-1以降の月ごとのヒ
ストグラム
ufo.us
<-‐‑‒
subset(ufo.us,
DateOccurred
>=
as.Date("1990-‐‑‒01-‐‑‒01"))
ufo.us$YearMonth
<-‐‑‒
strftime(ufo.us$DateOccurred,
format="%Y-‐‑‒%m")
ggplot(ufo.us,
aes(x
=
DateOccurred))
+
geom_̲histogram(aes(fill='white',
color='red'))
+
scale_̲fill_̲manual(values=c('white'='white'),
guide="none")
+
scale_̲color_̲manual(values=c('red'='red'),
guide="none")
+
scale_̲x_̲date(breaks
=
"50
years")
- 39. 時系列と頻度の処理
sightings.counts
<-‐‑‒
ddply(ufo.us,
.(USState,YearMonth),
nrow)
date.range
<-‐‑‒
seq.Date(from
=
as.Date(min(ufo.us$DateOccurred)),
to
=
as.Date(max(ufo.us$DateOccurred)),
by
=
"month")
date.strings
<-‐‑‒
strftime(date.range,
"%Y-‐‑‒%m")
states.dates
<-‐‑‒
lapply(state.abb,
function(s)
cbind(s,
date.strings))
states.dates
<-‐‑‒
data.frame(do.call(rbind,
states.dates),
stringsAsFactors
=
FALSE)
#
left
outer
join
all.sightings
<-‐‑‒
merge(states.dates,
sightings.counts,
by.x
=
c("s",
"date.strings"),
by.y
=
c("USState",
"YearMonth"),
all
=
TRUE)
names(all.sightings)
<-‐‑‒
c("State",
"YearMonth",
"Sightings")
all.sightings$Sightings[is.na(all.sightings$Sightings)]
<-‐‑‒
0
all.sightings$YearMonth
<-‐‑‒
as.Date(rep(date.range,
length(state.abb)))
all.sightings$State
<-‐‑‒
as.factor(all.sightings$State)
欠けている月の目撃情報を0として追加
州の要素を文字列から因子に変更する
- 40. 描画する
ggplot(all.sightings,
aes(x
=
YearMonth,y
=
Sightings))
+
geom_̲line(aes(color
=
"darkblue"))
+
facet_̲wrap(~∼State,
nrow
=
10,
ncol
=
5)
+
theme_̲bw()
+
scale_̲color_̲manual(values
=
c("darkblue"
=
"darkblue"),
guide
=
"none")
+
scale_̲x_̲date(breaks
=
"5
years",
labels
=
date_̲format('%Y'))
+
xlab("Years")
+
ylab("Number
of
Sightings")
+
opts(title="Number
of
UFO
sightings
by
Month-‐‑‒Year
and
U.S.
State
(1990-‐‑‒2010)")
- 41. 一章まとめ
! 可視化による分析をしました
! (考察は本を読むべし)
! Rでやるのもいいですがperl,ruby,pythonで処理して
からread.csvで読み込むのが普通かなと
! Pythonistaだったらpandasという選択肢もあります
! dataframe実装してある
! joinできる
! 速い(numpy)
- 44. 要約
! 行か列の圧縮
! 要約統計量
! 行の圧縮
! 平均とか中央値とか
! 次元削減
! 列の圧縮
! PCA,MDS
! 全部読み終わったらあらためて考えるとイイ
- 46. 標準偏差と分散
! データの広がりを表現したい
! バラツキを表現する
>
var(heights)
[1]
14.80347
>
mean(heights)
[1]
66.36756
>
c(mean(heights)-‐‑‒var(heights),
mean(heights)+var(heights))
[1]
51.56409
81.17103
あとで
- 48. 分布
! 分布の種類
! 正規分布
! ガンマ分布
! コーシー分布
! 単峰性か否か
! 双峰性の分布が重なって見かけ上単峰性になっていな
いか?
! ヒストグラムよりは密度推定のほうがよいとおもう
! バイオリンプロットとかbean-plotもおすすめ
- 50. 男女を予測
c
<-‐‑‒
coef(logit.mode)
ggplot(height.weights,
aes(x
=
Weight,
y=Height,
color=Gender))
+
geom_̲point()
+
stat_̲abline(intercept
=
-‐‑‒c[1]/c[2],
slope=-‐‑‒c[3]/c[2],
geom='abline',
color='black')