Skip to content

Instantly share code, notes, and snippets.

@smrmkt
Last active April 8, 2016 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smrmkt/764f46751c49d1b390c75d2aedb14427 to your computer and use it in GitHub Desktop.
Save smrmkt/764f46751c49d1b390c75d2aedb14427 to your computer and use it in GitHub Desktop.
optim() example
library(dplyr)
# 選択肢1, 2のデータを作成して結合
# 項目は以下の通り
# クラス番号
# 候補者1支持ダミー
# 候補者2支持ダミー
# 価値観1
# 価値観2
location1 <- matrix(c(rep(1, 100),
rep(1, 30), rep(0, 70),
rep(0, 30), rep(1, 70),
rep(1, 71), rep(0, 29),
rep(0.3, 69), rep(0.7, 31)), 100, 5)
location2 <- matrix(c(rep(2, 100),
rep(1, 50), rep(0,50),
rep(0, 50), rep(1,50),
rep(0.1, 40), rep(0.8, 20), rep(0.5, 40),
rep(0.2, 20), rep(1, 80)), 100, 5)
d <- as.data.frame(rbind(location1, location2))
colnames(d) <- c("class_id", "person1", "person2", "value1", "value2")
# クラス1, 2の支持率データ
# 項目は以下の通り
# クラス番号
# 候補者1支持率
# 候補者2支持率
s <- as.data.frame(t(matrix(c(1, 0.8, 0.2, 2, 0.6, 0.4), 3, 2)))
colnames(s) <- c("class_id", "support1", "support2")
# 結合してデータセットを作成
ds <- d %>% inner_join(s, by="class_id")
# 1クラスぶんにデータを絞る
# ds1 <- ds %>% filter(class_id==1)
# 最適化する関数
predict_rating <- function(b, d, print=FALSE) {
d_tmp <- d
d_tmp$predict1 <- b[1]*d_tmp$person1*b[3]*d_tmp$value1*b[4]*d_tmp$value2
d_tmp$predict2 <- b[2]*d_tmp$person2*b[3]*d_tmp$value1*b[4]*d_tmp$value2
# クラスidでグループ化して合計スコアを出した上で,比率に変換する
d_tmp2 <- d_tmp %>%
group_by(class_id, support1, support2) %>%
summarize(., predict1=sum(predict1), predict2=sum(predict2))
total <- d_tmp2$predict1+d_tmp2$predict2
d_tmp2$predict1 <- d_tmp2$predict1/total
d_tmp2$predict2 <- d_tmp2$predict2/total
if (print) {
print(d_tmp2)
}
# 最少化する関数は二乗誤差
sum((d_tmp2$support1-d_tmp2$predict1)^2+abs(d_tmp2$support2-d_tmp2$predict2)^2)
}
res <- optim(abs(rnorm(4, 1, 1)),
predict_rating,
d=ds,
method="L-BFGS-B",
lower=0,
upper=10,
control=list(maxit=10000))
res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment