Rstudio Serverの動作確認で使ったRとpythonのサンプル


Rstudio Serverの動作確認で使用したRとpythonのサンプルをメモとして残しておく

Rを実行したマシンのスペック確認

# https://www.karada-good.net/analyticsr/r-330/
#パッケージのインストール
# RHEL9+renv環境だとdevtoolsのインストールで失敗した
install.packages("rlang")
install.packages("devtools")
devtools::install_github("csgillespie/benchmarkme")
#パッケージの読み込み
library("benchmarkme")

#全てのベンチマークを実行:benchmark_stdコマンド
#各ベンチマークの詳細はヘルプを参照
res <- benchmark_std()
#結果をプロット
plot(res)

#CPU情報の取得:get_cpuコマンド
get_cpu()

#使用環境情報の取得:get_platform_infoコマンド
get_platform_info()

#使用中のRの情報を取得:get_r_versionコマンド
get_r_version()


#システム情報に関する全コマンドを実施:get_sys_detailsコマンド
#Sys.info(),get_platform_info(),get_r_version(),get_ram(),get_cpu()
#get_byte_compiler(),get_linear_algebra(),installed.packages(),実行時間のコマン ドを実施
#表示が多いので省略
get_sys_details()

Rでgrid描画のテスト

#http://www.okadajp.org/RWiki/?grid+%E3%83%91%E3%83%83%E3%82%B1%E3%83%BC%E3%82%B8%E4%BA%8B%E5%A7%8B

library(grid)

grid.multipanel(vp=viewport(0.5, 0.5, 0.8, 0.8))  # デモ(1)
grid.plot.and.legend()                            # デモ(2)
grid.plot.and.legend                              # 関数定義

grid.newpage()
#grid.arrows(x = c(0.25, 0.75), y = 0.5)
grid.circle(x=0.5, y=0.5, r=0.5)
grid.frame(name=NULL, gp=gpar(), vp=NULL)
grid.grill(h = seq(0.25, 0.75, 0.25), v = seq(0.25, 0.75, 0.25))

grid.lines(x = c(0.25, 0.75), y = 0.5)
grid.line.to(x=1, y=1)

grid.polygon(x=c(0, 0.5, 1, 0.5), y=c(0.5, 1, 0.5, 0))
grid.rect(x = 0.5, y = 0.5, width = 0.7, height = 0.3)
grid.segments(x0 = 0, y0 = 0, x1 = 0.5, y1 = 0.5)
grid.text(label="abc", x = 0.5, y = 0.5)
grid.text(label="g実験g", x = 0.8, y = 0.5)
grid.xaxis(at = NULL, label = T, main = T, name = NULL)
grid.yaxis(at = NULL, label = T, main = T, name = NULL)

pythonとtensorflow/cudaのサンプル

import tensorflow as tf
import torch
torch.cuda.is_available()

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)

rstanのサンプル

# http://www.psy.ritsumei.ac.jp/~hoshino/Wsl/

install.packages("rstan")
install.packages("cmdstanr", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
library(cmdstanr)
install_cmdstan()

# https://estuarine.jp/2018/01/install-rstan/
# https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started-(Japanese)
library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)

# 例 1: Eight Schools
schools_dat <- list(J = 8,
                    y = c(28,  8, -3,  7, -1,  1, 18, 12),
                    sigma = c(15, 10, 16, 11,  9, 11, 10, 18))
fit <- stan(file = 'rstan-sample-input.stan', data = schools_dat)
# ↑ の処理は時間がかかる
print(fit)
plot(fit)
pairs(fit, pars = c("mu", "tau", "lp__"))

la <- extract(fit, permuted = TRUE) # arraysのlistを返す
mu <- la$mu

### iterations, chains, parametersの3次元arrayを返す
a <- extract(fit, permuted = FALSE)

### stanfitオブジェクトにS3関数を使う
a2 <- as.array(fit)
m <- as.matrix(fit)
d <- as.data.frame(fit)

上記サンプル用のデータファイル rstan-sample-input.stan

data {
  int<lower=0> J;         // 学校の数
  real y[J];              // 推定されている教育の効果
  real<lower=0> sigma[J]; // 教育の効果の標準誤差
}

parameters {
  real mu;                // 処置の効果(全体平均)
  real<lower=0> tau;      // 処置の効果の標準偏差
  vector[J] eta;          // 学校ごとのスケール前のバラつき
}

transformed parameters {
  vector[J] theta = mu + tau * eta;        // 学校ごとの処置の効果
}

model {
  target += normal_lpdf(eta | 0, 1);       // 事前分布の対数密度
  target += normal_lpdf(y | theta, sigma); // 対数尤度
}

Rでラインを引く

# https://www.library.osaka-u.ac.jp/doc/TA_2014_01.pdf

temperature<-c(22,23,23,24,24,25,25,25,26,26)
coffee<-c(100,103,105,110,118,118,120,122,124,125)
plot(temperature,coffee)

plot(temperature,coffee,
     xlim=c(20,30),
     ylim=c(90,130),
     main=("コーヒーの売れ行き"),
     pch=17
)
prd<-lm(coffee~temperature)
abline(prd)