#多値ロジスティック
library(dummies)
data(iris)
data=data.frame(iris)
#学習率
mu=0.0001
#特徴量行列
X=as.matrix(data[,!(colnames(data) %in% c("Species"))])
#アヤメの種類
Species=unique(data$Species)
#目的変量の行列
Y=dummy(data$Species)
#重み係数
W=array(1,dim=c(ncol(X),length(Species)))
#閾値
b=array(1,dim=c(1,length(Species)))
#反復計算回数
ite=1000000
for(j in 1:ite){
Z=t(t(X%*%W)+c(b))
#予測確率(ソフトマックス)を入れる箱を用意
pthi_vec=array(0,dim=c(nrow(Z),length(Species)))
#予測確率の導入
for(i in 1:nrow(Z)){
pthi_vec[i,]=exp(Z[i,])/sum(exp(Z[i,]))
}
#重み行列の更新量を計算
dW=t(X)%*%(Y-pthi_vec)
#閾値の更新量の計算
db=array(1,dim=c(1,nrow(X)))%*%(Y-pthi_vec)
#重みの更新
W=W+mu*dW
#閾値の更新
b=b+mu*db
#交差エントロピーの計算
cross_entropy=-sum(Y*log(ifelse(pthi_vec>0,pthi_vec,1)))
print(cross_entropy)
}
#pre broyden
library(dummies)
data(iris)
data=data.frame(iris)
#学習率
mu=10^(-5)
#特徴量行列
X=as.matrix(data[,!(colnames(data) %in% c("Species"))])
#アヤメの種類
Species=unique(data$Species)
#目的変量の行列
Y=dummy(data$Species)
x_vec=rep(1,ncol(X)*length(Species)+length(Species))
f=function(x){
w_vec=x[1:(ncol(X)*length(Species))]
W=matrix(w_vec,ncol=length(Species))
b=x[(ncol(X)*length(Species)+1):length(x)]
Z=t(t(X%*%W)+c(b))
#予測確率(ソフトマックス)を入れる箱を用意
pthi_vec=array(0,dim=c(nrow(Z),length(Species)))
#予測確率の導入
for(i in 1:nrow(Z)){
pthi_vec[i,]=exp(Z[i,])/sum(exp(Z[i,]))
}
#重み行列の更新量を計算
dW=t(X)%*%(Y-pthi_vec)
#切片の更新量の計算
db=array(1,dim=c(1,nrow(X)))%*%(Y-pthi_vec)
return(c(c(dW),db))
}
#反復計算回数
ite=10^(6)
#ヤコビアンの初期値
H=diag(f(x_vec))
for(l in 1:ite){
#以前の座標点を保存
X_pre=x_vec
#座標点を更新
x_vec=x_vec-mu*H%*%f(x_vec)
#以前の座標点と更新された座標点の差のベクトル(s)
s=x_vec-X_pre
#以前の座標点と更新された座標点の関数値の差のベクトル(y)
y=f(x_vec)-f(X_pre)
#ヤコビアンの近似行列を更新する
H=H+((s-H%*%y)/as.numeric(t(s)%*%H%*%y))%*%t(s)%*%H
print(sum(abs(f(x_vec))))
}