-
-
Save aldente-hu/59e7aa967f7a529648e39f6669342e60 to your computer and use it in GitHub Desktop.
文字通りの最小二乗法を用いて指数関数近似を行う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# R言語の処理系がインストールされている必要があります(コマンドラインから `R --version` を実行してみましょう)。 | |
# また、環境変数R_HOMEが設定されていることを確認して下さい(値はRのライブラリのインストール先、例えば /usr/lib/R)。 | |
# さらに、Rubyのr-bridgeに依存しています。 https://rubygems.org/gems/r_bridge | |
# Usage: ruby strict_lsm.rb datafile | |
# datafileはn行100列(決め打ち)のCSVファイル。1列目がx、それ以降の列が各セットのyの値。 | |
# 結果は100行2列のCSV形式。1セットにつき1行で、1列目がaの値、2列目がbの値。 | |
# 標準出力に出力するので、ファイルに保存するときはシェルのリダイレクトを使って下さい。 | |
# Example. ruby strict_lsm.rb datafile > result | |
require 'r_bridge' | |
if (ARGV.size == 0) | |
puts "Usage: ruby #{$0} datafile (> result)" | |
else | |
all_data = [] | |
File.open(ARGV.first).each_line { |line| | |
unless line.strip.empty? | |
all_data << line.split(',').map(&:to_f) | |
end | |
} | |
x_array = all_data.map(&:first) | |
RBridge.init_embedded_r | |
begin | |
(1..100).each do |i| | |
y_array = all_data.map{ |array| array[i] } | |
df = RBridge.create_dataframe({"x" => x_array, "y" => y_array}) | |
f_array = ['y', '~', 'b', '*', 'exp', '(', 'a', '*', 'x', ')'] | |
formula = RBridge.create_formula_from_syms(f_array.map{ |c| RBridge::SymbolR.new(c) }) | |
start_list = RBridge.create_list({'a' => [-0.2], 'b' => [250]}) # 初期値をハードコード(手抜き) | |
reg = RBridge.exec_function(RBridge.create_function_call( | |
'nls', {'data' => df, 'formula' => formula, "start" => start_list}) | |
) | |
coef = RBridge.exec_function(RBridge.create_function_call("coefficients", {"object" => reg})) | |
RBridge.exec_function_no_return(RBridge.create_function_call("print", {'x' => coef})) | |
end | |
ensure | |
RBridge.gc_all | |
RBridge.end_embedded_r | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment