2024年12月12日木曜日
IPアドレスも過去の履歴をチェックする必要がある
2023年12月21日木曜日
メールシステムの裏側:SMTP、MDA、POP3の役割を解説
2021年5月12日水曜日
OCNモバイルone テザリングのためのAPN設定(マニュアル不記載)
2019年10月4日金曜日
aタグのhrefに書いた javascript がうまく動作しない
疑似プロトコルと呼ばれ、多用されています。
しかし、ブラウザの特定の環境下(※)では
別窓(新規タブ)が開いてしまうようになり、
スクリプトが動作しません。
■解決する方法の例:
<a href="javascript:sampleFunction();">戻る</a>
↓
<a href="#" onClick="sampleFunction();return false;">戻る</a>
上記のように修正します。
return false;は「#」によるページスクロール抑止のためです。
みなさんも、サイト内のコードをチェックしてみましょう。
エラーではないですが、動作の不具合を起こしやすいですし、
気が付きにくいです。
HTML Lint によると、疑似プロトコルは
Mozilla以外ではサポートされていません。
http://www.htmllint.net/html-lint/explain.html の235番。
今後は、
<a href="#" onClick="sampleFunction();return false;">
で書こうと思います。
-------------
※当方で問題があった環境:
Chromeの最新版 + プラグイン「Opens external links in a new tab1.0」
2019年5月13日月曜日
fail2ban / recidive error: エラー
2019-05-12 05:39:32,324 fail2ban.actions[19862]: WARNING [recidive] Ban XXX.XXX.XXX.XXX
2019-05-12 05:39:32,327 fail2ban.actions.action[19862]: ERROR ip route add blackhole XXX.XXX.XXX.XXX returned 200
2019-05-12 07:24:53,626 fail2ban.actions[19862]: INFO [recidive] XXX.XXX.XXX.XXX already banned
recidive Interfere with other action
postfixなど他の Ban/Unban と recidive の Ban が
干渉してうまく recidive が動作しない。
例えば、recidive がせっかく Ban したものを、他がUnbanしたり、
他が Ban した後に、recidive が Ban しようとして重複Banでコケる。
/etc/fail2ban/filter.d/recidive.conf
そこで上記を編集する。
*変更箇所(Change/Replace): Ban -> Unban
*Before
failregex = ^(%(__prefix_line)s|,\d{3} fail2ban.actions%(__pid_re)s?:\s+)WARNING\s+\[(?!%(_jailname)s\])(?:.*)\]\s+Ban\s+
*After
failregex = ^(%(__prefix_line)s|,\d{3} fail2ban.actions%(__pid_re)s?:\s+)WARNING\s+\[(?!%(_jailname)s\])(?:.*)\]\s+Unban\s+
これで干渉せず正しく動作するようになる。
Interfere will be solved.
CentOS7 / fail2ban0.8.12
2017年10月2日月曜日
外部サーバー(DB、SMTB、Redisなど)との疎通確認を簡単にする方法
netcatコマンドというのを使います。コマンド自体は、「nc」です。
# nc
<使うシチュエーション>
・複数台のサーバーでアプリケーションを構成する場合、
それらの間の、通信の確認だけをまず行いたいという時があると思います。
・プログラムソースレベルの問題なのか、
ネットワーク関連の問題なのかを切り分けるのにも使えます。
<ncコマンドが入っていない時>
# which nc で、インストール状態を確認して、
入っていないようでしたら
# sudo yum install nc nmap
または
# sudo apt-get install netcat
<コマンドの文法>
# nc -v 対象ホスト(IPアドレス等) ポート番号
「-v」により、通信の詳細を表示させます
-----------------------------------------------------------------
<利用例>
■SMTPサーバーとの疎通確認
(例)
SMTPサーバー: mail.sample.com
ポート番号: 25
↓
# nc -v mail.sample.com 25
出力
Connection to mail.sample.com 25 port [tcp/smtp] succeeded!
220 mail.sample.com ESMTP
接続はOKなようです。
Ctrl+C を打つと、もとに戻ります。
逆に、何もレスポンスが帰ってこないようでしたら、
ネットワーク的につながっていないということです。
確認ポイント:
- 相手サーバー名は正しいですか
- ポート番号は正しいですか
- ファイアーウォールなどで閉じていませんか(こっち側)
- ファイアーウォールなどで閉じていませんか(相手側)
- 相手側サーバーから、接続許可は出ていますか
- 相手側サーバーは、動いていますか
■DBサーバーとの疎通確認
(例)
DBサーバー: sql.sample.com
ポート番号: 3306
↓
# nc -v sql.sample.com 3306
出力
Connection to sql.sample.com 3306 port [tcp/ms-sql-s] succeeded!
接続はOKなようです。
何もレスポンスが帰ってこない場合については、前述のとおりです。
Ctrl+C を打つと、もとに戻ります。
■Redis /Elasticache サーバーとの疎通確認
(例)
DBサーバー: hoge.cache.amazonaws.com
ポート番号: 6379
↓
# nc -v hoge.cache.amazonaws.com 6379
出力
Connection to hoge.cache.amazonaws.com 6379 port [tcp/*] succeeded!
入力
set hoge 123 など
接続はOKなようです。
何もレスポンスが帰ってこない場合については、前述のとおりです。
Ctrl+C を打つと、もとに戻ります。
.
2017年6月24日土曜日
【Javascript】URLを分解する: parse the URL
var url ="https://example.com/dir1/dir2/index.php?aaa=111/bbb&bbb=7#hello";
var protocol= url.split(':')[0];
var hash = url.split('#')[1];
var query = url.split('#')[0].split('?')[1];
var host = url.split('#')[0].split('?')[0].split('/')[2];
var path = url.split('#')[0].split('?')[0].replace(host,"").replace(/^https*:[\/]{3}/,"");
console.log( protocol ); // https
console.log( host ); // example.com
console.log( path ); // dir1/dir2/index.php
console.log( query ); // aaa=111/bbb&bbb=7
console.log( hash ); // hello
2017年6月21日水曜日
pythonで機械学習:windowsで「Intel MKL」DLL エラー
Intel MKL FATAL ERROR: Cannot load mkl_core.dll
解決法:インテルのサイトから最新のMKLを入手する
https://software.intel.com/en-us/intel-mkl
から「w_mkl_2017.3.210.exe」をダウンロードする。
(メールアドレスの登録が必要です)
windows:
インストール先フォルダから
「 mkl_ 」で始まるdll類を、
C:\Windows\System32にコピー(上書き)する
解決した。
当方の環境:
Windows7-64bit, Python3.5.2 (anaconda) 64bit、mxnet
2017年5月31日水曜日
SSL設定「信頼されていません」エラーが出る原因
Apache2.2.15 + mod_ssl + openssl1.0.1
チェックリスト:
(1) SHA1でCSRを作っているため
(2) 鍵の長さが、2048ビット未満
(3) 中間証明書を指定し忘れている
(4) httpd.confの
・ conf全体のServerNameディレクティブ
・ バーチャルホスト設定部分のServerNameディレクティブ
が、同じドメイン名を指定していて
コンフリクトしている。
(5) Apache2.4.8以降では、中間証明書の扱いが変わるらしく
SSLCertificateChainFile は廃止される
今回ハマったのは、(4)でした。
バーチャルホストでいくらSSLCertificate類のディレクティブを
指定しても、一向に効きませんでしたが、その原因は
大元の(conf全体、バーチャルホストの外側)の、ServerNameが
優先して悪さをしていたっぽい。
参考: 設定後のhttpd.conf
・
・
ServerName dummy.hogehoge.jp:80
・
・
・中略
・
・
NameVirtualHost xxx.xxx.xxx.xxx:443
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES:!RC4:!DH
SSLHonorCipherOrder On
<VirtualHost xxx.xxx.xxx.xxx:443>
SSLEngine on
ServerName hogehoge.jp
ServerAdmin webmaster@hogehoge.jp
DocumentRoot /var/www/html/hogehoge
CustomLog logs/access_log combined
ErrorLog logs/error_log
Options FollowSymLinks
SSLCertificateKeyFile /etc/httpd/conf/ssl.key/2017.key
SSLCertificateChainFile /etc/httpd/conf/ssl.crt/2017.cer
SSLCertificateFile /etc/httpd/conf/ssl.crt/2017.crt
</VirtualHost>
2015年5月17日日曜日
Emeditor起動時の「アクセスが拒否されました」を表示させないようにする
2015年5月10日日曜日
プリインストール版のOffice2013の 32bit版を64bit版にする方法
まだまだMS的には32bit推奨なため、手順はややこしいです。
とりあえず、32bit版のOfficeはアンインストールせずに始めてみましょう。
焦らない焦らない ^ ^;
================================================
(1)アカウントページに行く。
https://downloadoffice.getmicrosoftkey.com
https://downloadoffice.getmicrosoftkey.com/Account/Index
※要ログイン
※要プロダクトキー
(2)「今すぐダウンロード」ボタンは押しません! ⇒ 32bit版になってしまうから。(Setup.x86.ja-JP_・・・・・.exeは32bit版)
↓
そこでまずは、「今すぐダウンロード」ボタンのリンクURLを取得します。
================================================
(2-1) リンクURL取得するには、緑色の「今すぐダウンロード」ボタンを右クリック→メニューから「ショートカットのコピー」 → クリップボードにURLが入ります
(2-2別の方法 )または、「今すぐダウンロード」でとりあえずダウンロードだけして、メニューから「ダウンロードの表示」で、ダウンロードの履歴を表示して → ファイル名を右クリック→メニューから「ダウンロードリンクのコピー」 → クリップボードにURLが入ります
================================================
URL の 中の"platform=x86" を "platform=x64" に変更して・・・
(4) ブラウザで開きます。
Setup.x64.ja-JP_・・・・・.exe(64bit版)がダウンロードされます。
================================================
ここまできたら64bit版の準備ができたことになりますので、
※できればここで復元ポイントを作成しましょう
(5) 32bit版のOfficeを アンインストールします。
(6) あとは、(4)の.exeファイルを実行(ダブルクリック)して、64bit版のインストーラーの指示どおりに進みます。
================================================
たぶん2010でも同じようなものだと思う。
当方:Windows7OS64bit、Office2007→ 2013 PI版 Home&Business 64bit
参考:プレインストール用の 64 ビット版 Office 2013 のインストール方法
http://support.microsoft.com/kb/2814147/JA
2015年5月3日日曜日
PHP:スクレイピングを簡単に行う関数
<?php
/* 利用例:sample
$val = fetch_val_from_URL_ver3 (
"http://www.yahoo.com/",
"/lang=\"([\s\S]+?)\"/i"
);
print_r ( $val ) ; //en-US
print "<br />";
$array= fetch_val_from_URL_ver3 (
"",
"/lang=\"([\w\-]+?)\"[\s\S]+?<title>([\s\S]+?)<\/title>/i"
);
print_r ( $array ) ; //Array ( [0] => [1] => en-US [2] => Yahoo )
print "<br />";
*/
function fetch_val_from_URL_ver3 ( $CRON_URL , $REGEX_val ) {
/*
★メモ:
・日本語を正規表現に含む場合は、UTF8でコードを書いて下さい。
それ以外は、関数の中のUTF-8に統一している箇所を修正してください。
・改行コードは正規表現が面倒になるので取得後に、一律削除しています。
★引数;
・CRON_URL は"http://~"からいれてください。
・CRON_URL を 空欄"" にすると、前回呼び出したHTMLを再利用します。
※ そのため、 $fv_global_html はグローバル変数名です。
・REGEX_val は正規表現です。
日本語を正規表現に含む場合は、UTF8で表現式を書いて下さい。
★返り値:
・REGEX_val の正規表現で、(かっこ) で囲った表現部分を抽出して、値または配列を返します。
・REGEX_val の (かっこ)が1個の時は、値を返します。2個以上の時は、配列を返します。
★バグシューティング:
・関数を記述しているPHPファイル は UTF-8 ですか? (スクレイプの対象ページの文字コードは関係ありません。
関数の中の mb_convert_encoding 処理で UTF8 に固定処理をしているからです。
もしこの関数を、UTF-8以外のスクリプトで記述する場合は、関数内のmb_convert_encoding部分を修正して下さい )
・正規表現は正しいですか? regexpal.com が便利ですよ。
・正規表現に、タグの </ があるときは 「<\/」にエスケープしてください
・この関数内で、$fv_global_html という変数名をグローバルとして利用しています。
★ヒント
・相手先のサーバーのためにも、同じページを何度も呼ばないようにしましょう。
CRON_URLを 空欄""にすると、前回呼び出した時のHTMLを再利用できます。
・改行を含む任意の一文字は [\s\S] 、 数値は ([\-\d\.\,]+?) を使うといいでしょう。
・UserAgentを変えるとこともできます
★その他
・無保証で無責任です。目的にかかわらず、自由に改変して利用できます。
クレジット表記や、連絡は不要です。
・バグ等のご連絡 は、sakai[-_atmark_-]quel.jp へ
・Programmed by Hiroyuki.Sakai, Infolio,inc.
*/
//設定
global $fv_global_html;
$flg_ReUse_contents = false;
unset($ary_match);
//取得
if ( $CRON_URL == "" ) {//urlがヌルの時は ReUse_contents をtrueに
$flg_ReUse_contents = true;
}
if ( $flg_ReUse_contents == true ) {
//$fv_global_htmlはそのまま再利用
if ( $fv_global_html =="" ) {//空かどうかのチェックだけ行う
print "No data URL:E:001 $CRON_URL ";
print "<br /> " ;
return false ;
}
}else {
//新規取得
//接続準備
$options = array(
'http' => array(
'method' => 'GET',
'header' => 'User-Agent: Mozilla/5.0 ( PHP fetch-val-from-URL-ver3 ) ',
),
);
$context = stream_context_create($options);
//取得
$fv_global_html = file_get_contents( $CRON_URL, false, $context);
$fv_global_html = str_replace ("\r\n","\n",$fv_global_html);
$fv_global_html = str_replace ("\r","\n",$fv_global_html);
//UTF8に統一する
$fv_global_html = mb_convert_encoding ($fv_global_html,"UTF-8",mb_detect_encoding($fv_global_html));
unset ( $context ) ;
}
//改行は正規表現が面倒になるので一律削除 (このブロックが不要であればコメントアウトしてください)
$fv_global_html = str_replace("\r","",$fv_global_html ) ;
$fv_global_html = str_replace("\n","",$fv_global_html) ;
//抽出
preg_match( $REGEX_val , $fv_global_html ,$ary_match );
//マッチがないとき
if ( isset($ary_match[1]) ) {
} else {
$val = "" ;
print "Nomatch E:003 <br />$REGEX_val<br />in $CRON_URL ";
print "<br /> " ;
return false ;
}
//数字ならばカンマ削除
$ary_match = array_map ( function ( $vn ) {
if ( preg_match("/[\d\.\,\/\s]+?/", $vn) ) {
return str_replace ( "," , "" , $vn ) ;
}else {
return $vn ;
}
} , $ary_match );
//配列か変数値を返す
if ( count($ary_match) == 2 ) {
return $ary_match[1];
}else {
$ary_match[0]=NULL;
return $ary_match;
}
}
?>
Search Keyword:
php, function, scraping , scraper class
2015年3月20日金曜日
解決法:Internet Explorer は動作を停止しました
2015年3月3日火曜日
GoogleのChromeブラウザで、お気に入りのアイコンが真っ白になる
ブックマークのアイコンが壊れたときは、次の手順でfaviconのキャッシュをクリアすると治りました。
Windows XPの場合:C:\Documents and Settings\<username>\Local Settings\Application Data\Google\Chrome\User Data\Default
Windows 7 or Vistaの場合:C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default
<username>はご自分のユーザーアカウントに使われている文字列に置き換えてください
MacOSXの場合:
~/Library/Application Support/Google/Chrome/Default/
2014年10月24日金曜日
Firefoxが起動しない!原因はハードウェアアクセラレーション
>> 一部のグラフィックカードとドライバの組み合わせによっては、ハードウェアアクセラレーションを利用すると、Firefox がクラッシュするか、ページ上のテキストやオブジェクトの表示に問題が起こることがあります。
- メニューボタン
をクリックし、オプション を選択します。 - 詳細 パネルを選択し、一般 タブを選択します。
- ハードウェアアクセラレーション機能を使用する (可能な場合) オプションをクリックしてチェックを外してください。
- メニューボタン
をクリックし、終了
をクリックします。 - Firefox を再び起動します。
これで解決した。
2014年9月30日火曜日
Unix思想
- モジュール化の原則 : クリーンなインターフェイスで結合される単純な部品を作れ。
"ぶざまな姿をさらさずに複雑なソフトウェアを書く唯一の方法は、全体としての複雑さの度合いを下げることだ""つまり、適切に定義されたインターフェイスで結び付けられた単純な部品からシステムを作り上げるのだ。 こうすれば、ほとんどの問題は局所化されるし、全体を壊さずに部品だけを改良することも不可能ではなくなる。"--『The Art of UNIX Programming』より
- 明確性の原則 : 巧妙になるより明確であれ。
- 組み立て部品の原則 : 他のプログラムと組み合わせられるように作れ。
- 分離の原則 : メカニズムからポリシーを切り離せ。エンジンからインターフェイスを切り離せ。
- 単純性の原則 : 単純になるように設計せよ。複雑な部分を追加するのは、どうしても必要なときだけに制限せよ。
- 倹約の原則 : 他のものでは代えられないことが明確に実証されない限り、大きなプログラムを書くな。
- 透明性の原則 : デバッグや調査が簡単になるように、わかりやすさを目指して設計せよ。
- 安定性の原則 : 安定性は、透明性と単純性から生まれる。
すべては変化する
仕様が固まることは無い
技術も常に進化する
こだわるな
最初から全部やろうとしない
どこからやるか
「何が一番やばいですか?」
最も困っているところから
お金、個人情報、……
新機能開発から
バグ修正のところから
迷ったらシンプルな方を選ぶ
シンプルさは信頼性の前提である(Dijkstra)
simple と easy は異なる(Rich Hicky の講演より)
エレガント
"Elegance is a combination of power and simplicity."
エレガンスは、力と単純性が結合して生まれる。
"Elegant code is not only correct but visibly, transparently correct."
エレガントなコードは、ただ正しいだけではなく目に見える透明な形で正しい。
Keep It Simple and Small
Keep It Small Stupid!
http://twada.herokuapp.com/presentations/wewlc/wewlc.html より
2014年8月4日月曜日
R言語:nnet:plot.nn:線が出ないときの対処方法
参考:http://hosho.ees.hokudai.ac.jp/~kubo/ce/NeuralNetwork.html
nnet()で作った neural network の例 (作図は久保先生の自作関数 plot.nn())
ただ、線が出ないときがある。ニューロンだけ表示されて、あとが真っ白という感じ。

↓
11行目
col.w = function(w) ifelse(w > 0, "#ff400040", "#0000ff40"),
このカラーコードが8桁になっているためであろう。
そこで、
色をここから選んで持ってきて
http://html-color-codes.info/japanese/
↓
修正した例
col.w = function(w) ifelse(w > 0, "#0000FF", "#FF0040"),
↓
線が出た

keywords: R nnet grahical graph draw figures bug display line show
余談ですが、線を太くしたいときは、10行目の w * 3 を w * 5 とか大きい数字に変えるとええで
2014年6月25日水曜日
OCR用のフォント、バーコード数字フォント

バーコードに使われている数字のフォントです。
有償版なら2万円ぐらい
http://www.flashbackj.com/ocr-b/
http://www.ricoh.co.jp/font/ など
エプソンLPユーザーなら
http://www.epson.jp/dl_soft/readme/7038.htm など
<無料>
非商用なら
≫Link:フォント http://ansuz.sooke.bc.ca/fonts-jp.php
海外のサイト(特に条件なし)OCR-A
http://sourceforge.net/projects/ocr-a-font/files/OCR-A/1.0/
OCR-AとB
http://sourceforge.jp/projects/tsukurimashou/releases/56948
上記のバックアップ
http://hp.vector.co.jp/authors/VA023120/data/OCRB.ttf
http://hp.vector.co.jp/authors/VA023120/data/OCRA.ttf
時系列データのシンプルな予測公式
- \(f \left(n+1\right) =2f \left(n\right) -f \left(n-1\right) \)
で、次の値を近似できる。
今日と昨日の値から、明日のデータ値を予測する感じです。
2次式を仮定するなら、
今日と昨日とおとといの値から、明日を予測する感じになる。
- \(f \left(n+1\right) =3f \left(n\right) -3f \left(n-1\right) +f \left(n-2\right) \)
上記で、次の値を近似できるものの・・・精度は下がる気がする。(結局一番最初の式がシンプルでベストなことがほとんどかもしれない)
。
以降、同様に順次漸化式を適用すれば
- \(f \left(n+1\right) =4f \left(n\right) -6f \left(n-1\right) +4f \left(n-2\right) -f \left(n-3\right) \)
- \(f \left(n+1\right) =5f \left(n\right) -10f \left(n-1\right) +10f \left(n-2\right) -5f \left(n-3\right) +f \left(n-4\right) \)
- :
係数は二項定理っぽくなりますが、あまり実用性はなさそう。
超単純なモデルによる外挿なので
誤差が多いことや長期予測には向かないことに注意しつつ
サクッと1点外挿したいときにどうぞ。
離散データをもっと正確にするには、
回帰分析、重回帰分析、ARIMAなどを検討しましょう。
2014年6月22日日曜日
PHP:単回帰分析(係数と重決定R2値)(1次関数~n次関数)
出典:http://PolynomialRegression.drque.net/
最新版は上記から取得してください。
PolynomialRegression.php のソース
class PolynomialRegression
{
private $xPowers;
private $xyPowers;
private $numberOfCoefficient;
private $forcedValue;
public function __construct( $numberOfCoefficient = 3 )
{
$this->numberOfCoefficient = $numberOfCoefficient;
$this->reset();
} // __construct
public function reset()
{
$this->forcedValue = array();
$this->xPowers = array();
$this->xyPowers = array();
$squares = ( $this->numberOfCoefficient - 1 ) * 2;
// Initialize power arrays.
for ( $index = 0; $index <= $squares; ++$index )
{
$this->xPowers[ $index ] = 0;
$this->xyPowers[ $index ] = 0;
}
} // reset
public function setDegree( $numberOfCoefficient )
{
$this->numberOfCoefficient = $numberOfCoefficient;
} // setDegree
public function setNumberOfCoefficient( $numberOfCoefficient )
{
$this->numberOfCoefficient = $numberOfCoefficient;
} // setNumberOfCoefficient
public function getNumberOfCoefficient( $numberOfCoefficient )
{
return $this->numberOfCoefficient;
} // getnumberOfCoefficient
public function setForcedCoefficient( $coefficient, $value )
{
$this->forcedValue[ $coefficient ] = $value;
} // setForcedCoefficient
public function getForcedCoefficient( $coefficient, $value )
{
$result = null;
if ( isset( $this->forcedValue[ $coefficient ] ) )
$result = $this->forcedValue[ $coefficient ];
return $result;
} // getForcedCoefficient
public function addData( $x, $y )
{
$squares = ( $this->numberOfCoefficient - 1 ) * 2;
// Remove the effect of the forced coefficient from this value.
foreach ( $this->forcedValue as $coefficient => $value )
{
$sub = bcpow( $x, $coefficient );
$sub = bcmul( $sub, $value );
$y = bcsub( $y, $sub );
}
// Accumulate new data to power sums.
for ( $index = 0; $index <= $squares; ++$index )
{
$this->xPowers[ $index ] =
bcadd( $this->xPowers[ $index ], bcpow( $x, $index ) );
$this->xyPowers[ $index ] =
bcadd
(
$this->xyPowers[ $index ],
bcmul( $y, bcpow( $x, $index ) )
);
}
} // addData
public function getCoefficients( $numberOfCoefficient = -1 )
{
// If no number of coefficients specified, use standard.
if ( $numberOfCoefficient == -1 )
$numberOfCoefficient = $this->numberOfCoefficient;
$matrix = array();
for ( $row = 0; $row < $numberOfCoefficient; ++$row )
{
$matrix[ $row ] = array();
for ( $column = 0; $column < $numberOfCoefficient; ++$column )
$matrix[ $row ][ $column ] =
$this->xPowers[ $row + $column ];
}
// Create augmented matrix by adding X*Y powers.
for ( $row = 0; $row < $numberOfCoefficient; ++$row )
$matrix[ $row ][ $numberOfCoefficient ] = $this->xyPowers[ $row ];
foreach ( $this->forcedValue as $coefficient => $value )
{
for ( $index = 0; $index < $numberOfCoefficient; ++$index )
{
$matrix[ $index ][ $coefficient ] = "0";
$matrix[ $coefficient ][ $index ] = "0";
}
$matrix[ $coefficient ][ $coefficient ] = "1";
$matrix[ $coefficient ][ $numberOfCoefficient ] = $value;
}
// Determine number of rows in matrix.
$rows = count( $matrix );
// Initialize done.
$isDone = array();
for ( $column = 0; $column < $rows; ++$column )
$isDone[ $column ] = false;
$order = array();
for ( $column = 0; $column < $rows; ++$column )
{
// Find a row to work with.
// A row that has a term in this column, and has not yet been
// reduced.
$activeRow = 0;
while ( ( ( 0 == $matrix[ $activeRow ][ $column ] )
|| ( $isDone[ $activeRow ] ) )
&& ( $activeRow < $rows ) )
{
++$activeRow;
}
// Do we have a term in this row?
if ( $activeRow < $rows )
{
// Remember the order.
$order[ $column ] = $activeRow;
// Normalize row--results in the first term being 1.
$firstTerm = $matrix[ $activeRow ][ $column ];
for ( $subColumn = $column; $subColumn <= $rows; ++$subColumn )
$matrix[ $activeRow ][ $subColumn ] =
bcdiv( $matrix[ $activeRow ][ $subColumn ], $firstTerm );
// This row is finished.
$isDone[ $activeRow ] = true;
// Subtract the active row from all rows that are not finished.
for ( $row = 0; $row < $rows; ++$row )
if ( ( ! $isDone[ $row ] )
&& ( 0 != $matrix[ $row ][ $column ] ) )
{
// Get first term in row.
$firstTerm = $matrix[ $row ][ $column ];
for ( $subColumn = $column; $subColumn <= $rows; ++$subColumn )
{
$accumulator = bcmul( $firstTerm, $matrix[ $activeRow ][ $subColumn ] );
$matrix[ $row ][ $subColumn ] =
bcsub( $matrix[ $row ][ $subColumn ], $accumulator );
}
}
}
}
// Reset done.
for ( $row = 0; $row < $rows; ++$row )
$isDone[ $row ] = false;
$coefficients = array();
for ( $column = ( $rows - 1 ); $column >= 0; --$column )
{
// The active row is based on order.
$activeRow = $order[ $column ];
// The active row is now finished.
$isDone[ $activeRow ] = true;
// For all rows not finished...
for ( $row = 0; $row < $rows; ++$row )
if ( ! $isDone[ $row ] )
{
$firstTerm = $matrix[ $row ][ $column ];
// Back substitution.
for ( $subColumn = $column; $subColumn <= $rows; ++$subColumn )
{
$accumulator =
bcmul( $firstTerm, $matrix[ $activeRow ][ $subColumn ] );
$matrix[ $row ][ $subColumn ] =
bcsub( $matrix[ $row ][ $subColumn ], $accumulator );
}
}
// Save this coefficient for the return.
$coefficients[ $column ] = $matrix[ $activeRow ][ $rows ];
}
// Coefficients are stored backward, so sort them.
ksort( $coefficients );
// Return the coefficients.
return $coefficients;
} // getCoefficients
static public function interpolate( $coefficients, $x )
{
$numberOfCoefficient = count( $coefficients );
$y = 0;
for ( $coefficentIndex = 0; $coefficentIndex < $numberOfCoefficient; ++$coefficentIndex )
{
// y += coefficients[ coefficentIndex ] * x^coefficentIndex
$y =
bcadd
(
$y,
bcmul
(
$coefficients[ $coefficentIndex ],
bcpow( $x, $coefficentIndex )
)
);
}
return floatval( $y );
} // interpolate
} // Class
テスト実行
データは、配列で指定する。 中の array(1,0),・・・が、array(Xの値,Yの値(目的変数))の順である。
require_once( 'inc_PolynomialRegression.php' ); //class読込
//テスト配列定義
$data = array (
array(1,0),
array(2,4),
array(3,3),
array(4,2),
array(5,5),
array(6,3),
array(7,8)
);
//print_r ( $data ) ;
// Precision digits in BC math.
bcscale( 10 );
// Start a regression class of order 2--linear regression.
$PolynomialRegression = new PolynomialRegression( 2 ); //変数の数、次数+1
// Add all the data to the regression analysis.
foreach ( $data as $dataPoint )
$PolynomialRegression->addData( $dataPoint[ 0 ], $dataPoint[ 1 ] );
// Get coefficients for the polynomial.
$coefficients = $PolynomialRegression->getCoefficients();
//
// Get average of Y-data.
//
$Y_Average = 0.0;
foreach ( $data as $dataPoint )
$Y_Average += $dataPoint[ 1 ];
$Y_Average /= count( $data );
//
// Calculate R Squared.
//
$Y_MeanSum = 0.0;
$Y_ErrorSum = 0.0;
foreach ( $data as $dataPoint )
{
$x = $dataPoint[ 0 ];
$y = $dataPoint[ 1 ];
$error = $y;
$error -= $PolynomialRegression->interpolate( $coefficients, $x );
$Y_ErrorSum += $error * $error;
$error = $y;
$error -= $Y_Average;
$Y_MeanSum += $error * $error;
}
$R_Squared = 1.0 - ( $Y_ErrorSum / $Y_MeanSum );
// Print slope and intercept of linear regression.
// 四捨五入 4桁目
$para_a = round( $coefficients[ 1 ], 4 );
$para_b = round( $coefficients[ 0 ], 4 );
$para_R = round( $R_Squared ,4 );
//結果出力
print "$para_a,$para_b,$para_R" ;
出力結果
0.8571,0.1429,0.5455
よって
y=0.8571 x + 0.1429
重決定 R2 は 0.5455
※X,Yの入れ替えに注意
エクセルとの比較:OK
二次関数で近似するときは
$PolynomialRegression = new PolynomialRegression( 3 );//2→3にする $para_a = round( $coefficients[ 2 ], 4 );//増やす $para_b = round( $coefficients[ 1 ], 4 ); $para_c = round( $coefficients[ 0 ], 4 ); $para_R = round( $R_Squared ,4 );
出力:0.0952,0.0952,1.2857,0.5657
エクセルと比較:OK
/*=========================================================================*/ /* Name: PolynomialRegression.php */ /* Uses: Calculates and returns coefficients for polynomial regression. */ /* Date: 06/01/2009 */ /* Author: Andrew Que (http://www.DrQue.net/) */ /* Revisions: */ /* 0.8 - 06/01/2009- QUE - Creation. */ /* 0.9 - 06/14/2012- QUE - */ /* + Bug fix: removed notice causes by uninitialized variable. */ /* + Converted naming convention. */ /* + Fix spelling errors (or the ones I found). */ /* + Changed to row-echelon method for solving matrix which is much */ /* faster than the determinant method. */ /* 0.91 - 05/17/2013- QUE - */ /* = Changed name to Polynonial regression as this is more fitting to */ /* to the function. */ /* 0.92 - 12/28/2013- QUE - */ /* + Added forced offset. */ /* 1.00 - 12/29/2013 - QUE - */ /* + Forced offset changed to allow any term to be forced. */ /* Unit complete. Correlation coefficient (r-squared) has been */ /* implemented externally in the demos. */ /* 1.1 - 2014/05/05 - QUE - */ /* + 'interpolate' is now static as it does not need an instance to */ /* operate. Useful if coefficients have been calculated elsewhere. */ /* - Deprecated 'setDegree' function. This is the wrong terminology for */ /* what the function does. It actually sets the number of */ /* coefficients for the polynomial. The degree of the polynomial is */ /* the number of coefficients less one. Made the identical function */ /* 'setNumberOfCoefficient' to replace it. */ /* + Added getter functions for anything that has a set function. */ /* */ /* This project is maintained at: */ /* http://PolynomialRegression.drque.net/ */ /* */ /* ----------------------------------------------------------------------- */ /* */ /* Polynomial regression class. */ /* Copyright (C) 2009, 2012-2014 Andrew Que */ /* */ /* This program is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program. If not, see
* Used for calculating polynomial regression coefficients. Useful for
* linear and non-linear regression, and polynomial curve fitting.
*
* @package PolynomialRegression
* @author Andrew Que ({@link http://www.DrQue.net/})
* @link http://PolynomialRegression.drque.net/ Project home page.
* @copyright Copyright (c) 2009, 2012-2014, Andrew Que
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version 1.1
*/
/**
* Used for calculating polynomial regression coefficients and interpolation using
* those coefficients. Useful for linear and non-linear regression, and polynomial
* curve fitting.
*
* Note: Requires BC math to be compiled into PHP. Higher-degree polynomials end up
* with very large/small numbers, requiring an arbitrary precision arithmetic. Make sure
* to set "bcscale" as coefficients will likely have decimal values.
*
* Quick example of using this unit to calculate linear regression (1st degree polynomial):
*
*
* $regression = new PolynomialRegression( 2 );
* // ...
* $regression->addData( $x, $y );
* // ...
* $coefficients = $regression->getCoefficients();
* // ...
* $y = $regression->interpolate( $coefficients, $x );
*
*
*
* @package PolynomialRegression
* @link http://PolynomialRegression.drque.net/ Project home page.









