<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>「LinearRegression」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/linearregression/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 11 Jan 2026 07:44:44 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「LinearRegression」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【scikit-learn】LinearRegressionで線形回帰をする方法</title>
		<link>https://tech.nkhn37.net/scikit-learn-linearregression-basic/</link>
					<comments>https://tech.nkhn37.net/scikit-learn-linearregression-basic/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Wed, 18 May 2022 20:00:00 +0000</pubDate>
				<category><![CDATA[scikit-learn]]></category>
		<category><![CDATA[LinearRegression]]></category>
		<category><![CDATA[線形回帰]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=3809</guid>

					<description><![CDATA[Pythonの機械学習ライブラリであるscikit-learnのLinearRegressionを使って線形回帰をする方法について解説します。 線形回帰 回帰分析は、予測したいデータに対して、既に与えられているデータから [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Pythonの機械学習ライブラリである<span class="marker"><strong>scikit-learn</strong></span>の<span class="marker"><strong>LinearRegression</strong></span>を使って線形回帰をする方法について解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">線形回帰</h2>



<p class="wp-block-paragraph"><span class="marker"><strong>回帰分析</strong></span>は、予測したいデータに対して、既に与えられているデータから関係性を推定することを言います。この時に$x^{2}$, $x^{3}$等の累乗の形がない線形の式で予測する回帰の事を<span class="marker"><strong>線形回帰</strong></span>と言います。</p>



<p class="wp-block-paragraph">例えば、簡単な直線を推定することを考えてみましょう。ある$(x, y)$のデータ群が与えられていたとします。この時、線形回帰モデルとして$y=ax + b$という数式を決めて当てはめることを考えます。線形回帰では、与えられたデータ$(x, y)$から$a$と$b$は何になるかということを推定します。</p>



<p class="wp-block-paragraph">$a$と$b$が分かると、与えられていない未知の$x$に対して$y$の値がどのようになるかを予測することができるようになります。</p>



<p class="wp-block-paragraph">Pythonでは<span class="marker"><strong>scikit-learn</strong></span>という機械学習ライブラリの<span class="marker"><strong>LinearRegression</strong></span>を使用することで線形回帰ができます。以降ではLinearRegressionの使用方法について紹介します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">scikit-learnのLinearRegressionで線形回帰を実装する方法</h2>



<p class="wp-block-paragraph">以降では、scikit-learnを使用します。インストールがされていない場合はpipでインストールをしておいてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install scikit-learn</pre>



<h3 class="wp-block-heading jinr-heading d--bold">線形単回帰</h3>



<p class="wp-block-paragraph"><span class="marker"><strong>線形単回帰</strong></span>とは、1つの予測したいデータ$y$を1つのデータ$x$から求める回帰分析方法です。式で表すと以下になります。</p>



<p class="wp-block-paragraph">\[<br>y = ax + b<br>\]</p>



<p class="wp-block-paragraph">この時、$(x, y)$の学習データがあった時に$a$や$b$を推定します。$a$は係数、$b$はバイアスとも言われます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">実装例</h4>



<p class="wp-block-paragraph">線形単回帰は、scikit-learnのLinearRegressionを使用して以下のようなプログラムで実行できます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split


def main():
    rs = np.random.RandomState(123)

    # ===== 線形回帰を行うためのデータを生成する
    bias = 5.0
    x, y, coef = make_regression(
        n_samples=100,
        n_features=1,
        n_targets=1,
        coef=True,
        bias=bias,
        noise=5.0,
        random_state=rs,
    )
    np.set_printoptions(precision=3, suppress=True)
    print(f"true coef: {coef:.3f}")
    print(f"true bias: {bias:.3f}")
    plt.plot(x, y, ".")

    # 訓練用データとテスト用データを分割する
    train_x, test_x, train_y, test_y = train_test_split(x, y, random_state=rs)

    # ===== 線形単回帰モデルを生成する
    model = LinearRegression(fit_intercept=True)

    # ===== モデルを学習する
    model.fit(train_x, train_y)

    # 推定結果の表示
    print(f"coef: {model.coef_}")
    print(f"bias: {model.intercept_:.3f}")
    print(f"R2: {model.score(test_x, test_y):.3f}")

    # ===== 線形回帰結果の線を引く
    xfit = np.linspace(np.min(x), np.max(x), 1000)
    # Y軸はpredictを実行して計算
    yfit = model.predict(xfit[:, np.newaxis])
    plt.plot(xfit, yfit)
    plt.show()


if __name__ == "__main__":
    main()</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
true coef: 33.867
true bias: 5.000
coef: [34.185]
bias: 4.611
R2: 0.982</pre>



<p class="wp-block-paragraph"><strong>【表示結果】</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="637" height="478" src="https://tech.nkhn37.net/wp-content/uploads/2022/09/image-26.png" alt="Python scikit-learn 線形単回帰結果" class="wp-image-5014" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/09/image-26.png 637w, https://tech.nkhn37.net/wp-content/uploads/2022/09/image-26-300x225.png 300w" sizes="(max-width: 637px) 100vw, 637px" /></figure>
</div>


<p class="wp-block-paragraph">青色のプロット点が与えられたデータです。それに対して、オレンジの線がモデルに当てはめて予測した直線になります。ぱっと見でデータの特徴を捉えられた直線になっていそうだないうことは分かるのではないかなと思います。</p>



<h4 class="wp-block-heading jinr-heading d--bold">実装内容の解説</h4>



<p class="wp-block-paragraph">上記で紹介した実装例の各部分ごとの内容を説明していきます。</p>



<p class="wp-block-paragraph"><strong>必要モジュールのインポート</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split</pre>



<p class="wp-block-paragraph">まずは、各種必要なライブラリをインポートします。線形回帰については、<span class="marker"><strong>sklearn.linear_model</strong></span>から<span class="marker"><strong>LinearRegression</strong></span>をインポートします。</p>



<p class="wp-block-paragraph">また、データ生成用のlinear_model.make_regression、テストデータ分割用のmodel_selection.train_test_splitもsklearnからインポートします。</p>



<p class="wp-block-paragraph">numpyやmatplotlibは分析に使うデータの処理や可視化のために使用します。</p>



<p class="wp-block-paragraph"><strong>データセットの用意</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # ===== 線形回帰を行うためのデータを生成する
    bias = 5.0
    x, y, coef = make_regression(
        n_samples=100,
        n_features=1,
        n_targets=1,
        coef=True,
        bias=bias,
        noise=5.0,
        random_state=rs,
    )
    np.set_printoptions(precision=3, suppress=True)
    print(f"true coef: {coef:.3f}")
    print(f"true bias: {bias:.3f}")
    plt.plot(x, y, ".")

    # 訓練用データとテスト用データを分割する
    train_x, test_x, train_y, test_y = train_test_split(x, y, random_state=rs)</pre>



<p class="wp-block-paragraph">今回は、sklearn.datasets.make_regressionを使ってデータを用意しています。各引数の意味は以下の通りです。単回帰用のデータは$x$、$y$でそれぞれ一次元なので、n_features=1, n_targets=1としています。返却されたcoefとbiasが(x, y)から予測するべき真の係数ということになります。</p>



<ul class="wp-block-list jinr-list">
<li>n_samples: データ数</li>



<li>n_features: 特徴数($x$)</li>



<li>n_targets: 目標値($y$)</li>



<li>coef: データを生成した線形モデルの係数を返却するか否か（True: 返却）</li>



<li>bias: バイアス</li>



<li>noise: データに加えるガウスノイズの標準偏差</li>



<li>random_state: 乱数のシード</li>
</ul>



<p class="wp-block-paragraph">また、学習用データとテスト用データを分割するためにtrain_test_splitで生成したデータを分割しています。</p>



<p class="wp-block-paragraph"><strong>線形回帰モデルの生成と学習</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # ===== 線形単回帰モデルを生成する
    model = LinearRegression(fit_intercept=True)

    # ===== モデルを学習する
    model.fit(train_x, train_y)

    # 推定結果の表示
    print(f"coef: {model.coef_}")
    print(f"bias: {model.intercept_:.3f}")
    print(f"R2: {model.score(test_x, test_y):.3f}")</pre>



<p class="wp-block-paragraph">上記の部分で線形回帰モデルを生成して学習しています。fit_interceptは、Trueにすることでバイアスの予測も行います。</p>



<p class="wp-block-paragraph">線形回帰を実行しているのは、<span class="marker"><strong>fit</strong></span>メソッドです。学習用データのtrain_xとtrain_yを引数に渡します。線形回帰結果は、modelの<span class="marker"><strong>coef_</strong></span>と<span class="marker"><strong>intercept_</strong></span>から取得することができます。結果としてはデータ生成時の真値に近い値が得られていることが分かるかと思います。</p>



<p class="wp-block-paragraph">ただ、係数の単純に値が近いというだけだとどれだけの精度があるのかが評価できません。線形回帰では、予測データと実際の正解データがどれぐらい一致しているのかを示す指標として決定係数$R^{2}$というものがよく使用されます。決定係数の定義は複数ありますが、scikit-learnで計算される$R^{2}$の定義は以下の通りです。</p>



<p class="wp-block-paragraph">\[<br>R^{2} = 1 &#8211; \frac{\sum_{i}(y_{i}-\hat{y}_{i})^{2}}{\sum_{i}(y_{i}-\bar{y})^{2}}<br>\]</p>



<p class="wp-block-paragraph">$\hat{y}$は予測された$y$で、$\bar{y}$は$y_{i}$の平均値です。決定係数は、精度がよいほど1に近くなります。0.8以上の数値であれば精度よく予測できていると言えるので今回の例では十分な精度が出ているということができます。</p>



<p class="wp-block-paragraph">なお、取得は簡単で<span class="marker"><strong>score</strong></span>メソッドに、テスト用のtest_x, test_yを渡すことで$R^{2}$を計算してくれます。</p>



<p class="wp-block-paragraph"><strong>回帰直線の描画</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # ===== 線形回帰結果の線を引く
    xfit = np.linspace(np.min(x), np.max(x), 1000)
    # Y軸はpredictを実行して計算
    yfit = model.predict(xfit[:, np.newaxis])
    plt.plot(xfit, yfit)
    plt.show()</pre>



<p class="wp-block-paragraph">上記部分は、未知の値(xfit)に対する予測(yfit)をしているところです。結果については、matplotlibのplotで描画しています。</p>



<h3 class="wp-block-heading jinr-heading d--bold">線形重回帰</h3>



<p class="wp-block-paragraph"><span class="marker"><strong>線形重回帰</strong></span>とは、1つの予測したいデータ$y$を複数のデータ$x_{i}$から求める回帰分析方法です。式で表すと以下になります。</p>



<p class="wp-block-paragraph">\[<br>y = \beta_{0}x_{0}+\beta_{1}x_{1}+\beta_{2}x_{2}+&#8230;+\epsilon<br>\]</p>



<p class="wp-block-paragraph">$(x_{0}, x_{1}, x_{2},&#8230;,x_{n})$と$y$のセットの学習データから、係数$\beta_{i}$とバイアス$\epsilon$を推定します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">実装例</h4>



<p class="wp-block-paragraph">線形重回帰は、単回帰と同じようにscikit-learnのLinearRegressionを使用して以下のようなプログラムで実行できます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split


def main():
    rs = np.random.RandomState(123)

    # ===== 線形重回帰を行うためのデータを生成する
    bias = 5.0
    x, y, coef = make_regression(
        n_samples=10000,
        n_features=10,
        n_informative=3,
        n_targets=1,
        coef=True,
        bias=bias,
        noise=5.0,
        random_state=rs,
    )
    np.set_printoptions(precision=3, suppress=True)
    print(f"true coef: {coef}")
    print(f"true bias: {bias:.3f}")

    # 学習用データとテスト用データを分割する
    train_x, test_x, train_y, test_y = train_test_split(x, y, random_state=rs)

    # ===== 線形重回帰モデルを生成する
    model = LinearRegression(fit_intercept=True)

    # ===== モデルを学習する
    model.fit(train_x, train_y)

    # パラメータを表示する
    print(f"coef: {model.coef_}")
    print(f"bias: {model.intercept_:.3f}")
    print(f"R2: {model.score(test_x, test_y):.3f}")


if __name__ == "__main__":
    main()</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果例】
true coef: [ 0.     0.     0.     0.    64.063  0.    96.22   0.     0.    91.392]
true bias: 5.000
coef: [ 0.01   0.065 -0.208 -0.041 64.05   0.082 96.311 -0.03   0.012 91.432]
bias: 4.897
R2: 0.999</pre>



<h4 class="wp-block-heading jinr-heading d--bold">実装内容の解説</h4>



<p class="wp-block-paragraph">重回帰と言いつつも単回帰と実装方法は同じですので少し異なる部分のみ説明します。</p>



<p class="wp-block-paragraph"><strong>データセットの用意</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # ===== 線形重回帰を行うためのデータを生成する
    bias = 5.0
    x, y, coef = make_regression(
        n_samples=10000,
        n_features=10,
        n_informative=3,
        n_targets=1,
        coef=True,
        bias=bias,
        noise=5.0,
        random_state=rs,
    )</pre>



<p class="wp-block-paragraph">データを生成するときにn_featureを10としています。これは$x_{0}$~$x_{9}$までの10の特徴を持つデータを用意していることを意味しています。$y$は一つなので、n_targets=1です。</p>



<p class="wp-block-paragraph">n_infomativeは、変数のうち$y$を説明するのに寄与している変数の数を指定しています。今回3を指定しているため、10変数あるわけですが、yの変化に影響を与えるのは3変数のみであることを示しています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">true coef: [ 0.     0.     0.     0.    64.063  0.    96.22   0.     0.    91.392]</pre>



<p class="wp-block-paragraph">上記のようにデータ生成時に返却される真値であるcoefを見てもらえば分かりますが、3つの部分しか係数に値を持っていません。数式でいうところの$y = \beta_{0}x_{0}+\beta_{1}x_{1}+\beta_{2}x_{2}+&#8230;+\epsilon$の中で$\beta$が0ということですので、$x$がどんな値をとろうが、$y$の値は変わりません。</p>



<p class="wp-block-paragraph"><strong>線形回帰モデルの生成と学習</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # ===== 線形重回帰モデルを生成する
    model = LinearRegression(fit_intercept=True)

    # ===== モデルを学習する
    model.fit(train_x, train_y)

    # パラメータを表示する
    print(f"coef: {model.coef_}")
    print(f"bias: {model.intercept_:.3f}")
    print(f"R2: {model.score(test_x, test_y):.3f}")</pre>



<p class="wp-block-paragraph">上記の部分を見てもらえば分かりますが、重回帰であろうがプログラムの方法は変わりません。結果について見てみましょう。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">true coef: [ 0.     0.     0.     0.    64.063  0.    96.22   0.     0.    91.392]
true bias: 5.000
coef: [ 0.01   0.065 -0.208 -0.041 64.05   0.082 96.311 -0.03   0.012 91.432]
bias: 4.897
R2: 0.999</pre>



<p class="wp-block-paragraph">ちゃんと真の係数が0になっているところは0に近い係数が予測できていますし、値を持っているところは近い値を予測できています。また、決定係数も1に近いことから精度よく予測できていることが分かります。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph"><span class="marker"><strong>scikit-learn</strong></span>の<span class="marker"><strong>LinearRegression</strong></span>を使用して線形回帰する方法について紹介してきました。簡単なコードで線形回帰によるデータ予測ができることが理解いただけたかと思います。</p>



<p class="wp-block-paragraph">このようにデータに対してモデルの当てはめができると例えば、データがどのような傾向でで増加していく（又は減少していく）傾向があるのかなどを簡単に調べることができます。是非、色々なデータに対して線形回帰を試してみていただけたらと思います。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><code>sklearn.linear_model.LinearRegression</code> の公式ドキュメントは<a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html" target="_blank" rel="noreferrer noopener">こちら</a>を参考にしてください。</p>
</div>
		</div></section>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては <a href="https://github.com/nkhn37/python-tech-sample-source/tree/main/python-data-analysis/scikit-learn/linear-regression" target="_blank" rel="noreferrer noopener">GitHub</a> にて公開しています。参考にしていただければと思います。</p>
</div></div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/scikit-learn-linearregression-basic/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-06-13 12:32:11 by W3 Total Cache
-->