sklearnのロジスティック回帰で求めた重みとバイアスを取得する方法.
scikit-learnはpythonで扱う機械学習のライブラリです.
非常に多くの機械学習に関する関数が提供されており,マニュアルも充実しているので重宝しています.
ただ,ロジスティック回帰で学習した後の最適な重みとバイアスだけ取得して,別の言語で予測は行いたいといったことがあります.(私だけかもしれませんが...)
github上のコードを読んでみると,
https://github.com/scikit-learn/scikit-learn
名前 | 場所 |
---|---|
重みw | LogisticRegression.coef_ |
バイアスb | LogisticRegression.intercept_ |
で得られることが分かります.
下記には,scikit-learnで予測した場合と,自前で予測した場合で一致していることが確認できます.
>>> import sklearn.linear_model >>> import numpy as np >>> estimator = sklearn.linear_model.LogisticRegression() >>> X = [[1,2], [2,1], [1,1], [2,2]] >>> y = [0, 0, 0, 1] >>> estimator.fit(X, y) LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, penalty='l2', random_state=None, tol=0.0001) >>> x_test = [2, 2] >>> estimator.predict_proba(x_test)[0][0] 0.66828548705463642 >>> (1 / (1 + np.exp(np.dot(c.coef_, x_test) + c.intercept_)))[0] 0.66828548705463653