<?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>「サポートベクターマシン」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/%E3%82%B5%E3%83%9D%E3%83%BC%E3%83%88%E3%83%99%E3%82%AF%E3%82%BF%E3%83%BC%E3%83%9E%E3%82%B7%E3%83%B3/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 11 Jan 2026 07:41:46 +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>「サポートベクターマシン」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【scikit-learn】サポートベクターマシン（SVM）の使用方法</title>
		<link>https://tech.nkhn37.net/scikit-learn-svm/</link>
					<comments>https://tech.nkhn37.net/scikit-learn-svm/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Fri, 03 Jun 2022 20:00:00 +0000</pubDate>
				<category><![CDATA[scikit-learn]]></category>
		<category><![CDATA[SVC]]></category>
		<category><![CDATA[SVM]]></category>
		<category><![CDATA[サポートベクターマシン]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=3889</guid>

					<description><![CDATA[Pythonの機械学習ライブラリであるscikit-learnを使ってサポートベクターマシン(SVM)を使用する方法について解説します。 サポートベクターマシン（SVM） サポートベクターマシン（SVM）は、教師ありの機 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Pythonの機械学習ライブラリである<span class="marker"><strong>scikit-learn</strong></span>を使って<span class="marker"><strong>サポートベクターマシン(SVM)</strong></span>を使用する方法について解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">サポートベクターマシン（SVM）</h2>



<p class="wp-block-paragraph"><span class="marker"><strong>サポートベクターマシン（SVM）</strong></span>は、教師ありの機械学習で用いるパターン認識のモデルの一つです。サポートベクターマシンは、分類問題や回帰問題へ適用できるモデルとなっています。</p>



<p class="wp-block-paragraph">サポートベクターマシンの理解で重要になってくるのが「<span class="marker"><strong>サポートベクター</strong></span>」と「<span class="marker"><strong>マージンの最大化</strong></span>」です。以下の画像でイメージしてみましょう。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" width="1001" height="666" src="https://tech.nkhn37.net/wp-content/uploads/2022/06/image.png" alt="" class="wp-image-3892" style="width:501px;height:333px" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/06/image.png 1001w, https://tech.nkhn37.net/wp-content/uploads/2022/06/image-300x200.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/06/image-768x511.png 768w" sizes="(max-width: 1001px) 100vw, 1001px" /></figure>
</div>


<p class="wp-block-paragraph">上記は、〇と△のデータを線形に分類する場合を例にしたものです。この時、二つのデータを分類するような直線は緑線や黄線のようにいくつも引けるかと思います。直線に並行するような領域（薄い色の範囲）を広げていくと、各データに接するようなデータ（点線で丸で囲んだ点）があります。このようなデータを「サポートベクター」と言います。そして、線からサポートベクターまでの距離(幅)を「マージン」と言います。</p>



<p class="wp-block-paragraph">サポートベクターマシンは、このマージンを最大化するようなモデルが最適なモデルとして選択されます。上記は簡単な線形での分類の例ですが、サポートベクターマシンではカーネル法と組み合わせることで非線形な分類や回帰にも適用できます。</p>



<p class="wp-block-paragraph">また、上記のようにきれいに分類できる例ではいいですが、境界線があいまいなデータが世の中にはたくさん存在します。このような場合には、<span class="marker"><strong>ソフトマージン</strong></span>と言って、多少のデータはマージンの中に入っても構わないとするような方法があります。</p>



<p class="wp-block-paragraph">この記事では、Pythonの機械学習ライブラリである<span class="marker"><strong>scikit-learn</strong></span>を用いてサポートベクターマシン（SVM）を使ったデータの分類をする方法を紹介していきます。</p>



<p class="wp-block-paragraph">scikit-learnの使い方に焦点を置くため、細かな理論は説明はしません。詳しく勉強したい人は以下の書籍が参考になります。SVMに関する内容は下巻に記載されています。上巻で、確率論や線形回帰、線形識別、ニューラルネットワークといったベースとなる内容が書かれているため、上巻を読んでからの方がより理解が進むかもしれません。私の場合は、大学の研究室で輪講という形で勉強して発表したりしていました。正直高い＆難しい部類の本ですが、理解できると非常に価値がある書籍であると思います。</p>







<h2 class="wp-block-heading jinr-heading d--bold">scikit-learnでサポートベクターマシン（SVM）を使用する方法</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">サポートベクターマシン（SVM）を使用した分類（sklearn.svm.SVC）</h3>



<p class="wp-block-paragraph">サポートベクターマシン（SVM）を使用した分類では、<span class="marker"><strong>sklearn.svm.SVC</strong></span>を使用します。以降では、線形分類の例と非線形分類の例を紹介します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">線形分類</h4>



<p class="wp-block-paragraph">データを線形に分類する簡単な例でサポートベクターマシンを適用してみます。以下のサンプルプログラムを用いて紹介します。</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_blobs
from sklearn.svm import SVC


def show_svm_result(svm_model, ax=None):
    """SVMの結果を表示する

    Args:
        svm_model: SVM学習結果モデル
        ax: axisの指定 (デフォルト: None)
    """
    if ax is None:
        ax = plt.gca()
    n_grid = 50

    xlim, ylim = ax.get_xlim(), ax.get_ylim()
    x = np.linspace(xlim[0], xlim[1], n_grid)
    y = np.linspace(ylim[0], ylim[1], n_grid)
    ygrid, xgrid = np.meshgrid(y, x)
    xygrid = np.vstack([xgrid.ravel(), ygrid.ravel()]).T
    decision = svm_model.decision_function(xygrid).reshape(xgrid.shape)

    # 境界線、マージンを表示
    ax.contour(
        xgrid,
        ygrid,
        decision,
        colors="k",
        levels=[-1, 0, 1],
        linestyles=["--", "-", "--"],
        alpha=0.5,
    )
    # サポートベクターを表示
    ax.scatter(
        svm_model.support_vectors_[:, 0],
        svm_model.support_vectors_[:, 1],
        s=100,
        linewidth=1,
        facecolor="none",
        edgecolor="r",
        label="Support Vector",
    )
    ax.legend()
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)


def main():
    """メイン関数"""
    np.random.seed(0)

    # ===== データの生成
    data, label = make_blobs(n_samples=100, centers=2, cluster_std=0.5)

    plt.scatter(data[label == 0, 0], data[label == 0, 1], marker="o")
    plt.scatter(data[label == 1, 0], data[label == 1, 1], marker="^")

    # ===== サポートベクターマシンを用いた学習
    model = SVC(kernel="linear", C=1.0e10)
    model.fit(data, label)
    print(model)
    print(model.support_vectors_)

    # ===== svmの結果表示
    show_svm_result(model)

    # 描画
    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="">【実行結果】
SVC(C=10000000000.0, kernel='linear')
[[0.5323772  3.31338909]
 [2.11114739 3.57660449]
 [1.46870582 1.86947425]]</pre>



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


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="433" height="333" src="https://tech.nkhn37.net/wp-content/uploads/2022/06/image-1.png" alt="scikit-learn SVM Linear" class="wp-image-3933" style="width:433px;height:333px" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/06/image-1.png 433w, https://tech.nkhn37.net/wp-content/uploads/2022/06/image-1-300x231.png 300w" sizes="(max-width: 433px) 100vw, 433px" /></figure>
</div>


<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_blobs
from sklearn.svm import SVC</pre>



<p class="wp-block-paragraph">サポートベクターマシンのSVMでの分類を実施するには<span class="marker"><strong>sklearn.svm</strong></span>から<span class="marker"><strong>SVC</strong></span>（Support Vector Classification）をインポートします。また、対象データの生成用にsklearn.datasetsからmake_blobsをインポートしています。</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="">    np.random.seed(0)

    # ===== データの生成
    data, label = make_blobs(n_samples=100, centers=2, cluster_std=0.5)

    plt.scatter(data[label == 0, 0], data[label == 0, 1], marker="o")
    plt.scatter(data[label == 1, 0], data[label == 1, 1], marker="^")</pre>



<p class="wp-block-paragraph">SVMの分類対象となるデータを用意し、プロットしている部分です。make_blobsを使用すると簡単にサンプルデータが作成できます。今回指定しているのは以下のような引数です。値を変えたり、コメントアウトしたりして色々なデータで試してみてください。</p>



<ul class="wp-block-list jinr-list">
<li>n_samples：データサンプル数</li>



<li>centers：データ集合の中心の数</li>



<li>cluster_std：各データ集合の標準偏差</li>
</ul>



<p class="wp-block-paragraph">乱数シードは上記例では、np.random.seedで設定していますが、make_blobsのrandom_state引数で指定することも可能です。</p>



<p class="wp-block-paragraph"><strong>SVC（Support Vector Classification）の実行</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 = SVC(kernel="linear", C=1.0e10)
    model.fit(data, label)
    print(model)
    print(model.support_vectors_)</pre>



<p class="wp-block-paragraph">上記が本題のサポートベクターマシンの学習を実行している部分です。今回は線形分類なので、<span class="marker"><strong>kernel</strong></span>として&#8221;linear&#8221;を指定してます。</p>



<p class="wp-block-paragraph"><span class="marker"><strong>C</strong></span>はマージンの硬さをコントロールするためのパラメータです。Cが非常に大きな値の場合は、マージンは硬いためデータ点はマージンの中に入れません。一方で小さなCの場合はマージンは柔らかくなり、いくつかの点を包含することが可能になります（ソフトマージン）。SMVを実行しているのは<span class="marker"><strong>fit</strong></span>メソッドです。</p>



<p class="wp-block-paragraph"><strong>結果の可視化</strong></p>



<p class="wp-block-paragraph">show_svm_resultは、SVMの実行結果を可視化するため用に用意した関数になります。詳細は細かくは説明しませんが、SVMの境界線とサポートベクターを表示しています。</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="">def show_svm_result(svm_model, ax=None):
    """SVMの結果を表示する

    Args:
        svm_model: SVM学習結果モデル
        ax: axisの指定 (デフォルト: None)
    """
    if ax is None:
        ax = plt.gca()
    n_grid = 50

    xlim, ylim = ax.get_xlim(), ax.get_ylim()
    x = np.linspace(xlim[0], xlim[1], n_grid)
    y = np.linspace(ylim[0], ylim[1], n_grid)
    ygrid, xgrid = np.meshgrid(y, x)
    xygrid = np.vstack([xgrid.ravel(), ygrid.ravel()]).T
    decision = svm_model.decision_function(xygrid).reshape(xgrid.shape)

    # 境界線、マージンを表示
    ax.contour(
        xgrid,
        ygrid,
        decision,
        colors="k",
        levels=[-1, 0, 1],
        linestyles=["--", "-", "--"],
        alpha=0.5,
    )
    # サポートベクターを表示
    ax.scatter(
        svm_model.support_vectors_[:, 0],
        svm_model.support_vectors_[:, 1],
        s=100,
        linewidth=1,
        facecolor="none",
        edgecolor="r",
        label="Support Vector",
    )
    ax.legend()
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)</pre>



<p class="wp-block-paragraph"><strong>実行結果の確認</strong></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="">【実行結果（再掲）】
SVC(C=10000000000.0, kernel='linear')
[[0.5323772  3.31338909]
 [2.11114739 3.57660449]
 [1.46870582 1.86947425]]</pre>



<p class="wp-block-paragraph">【表示結果（再掲）】</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="433" height="333" src="https://tech.nkhn37.net/wp-content/uploads/2022/06/image-1.png" alt="scikit-learn SVM Linear" class="wp-image-3933" style="width:433px;height:333px" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/06/image-1.png 433w, https://tech.nkhn37.net/wp-content/uploads/2022/06/image-1-300x231.png 300w" sizes="(max-width: 433px) 100vw, 433px" /></figure>
</div>


<p class="wp-block-paragraph">サポートベクターとして選択された点は「model.<span class="marker"><strong>support_vectors_</strong></span>」で取得ができます。上記の例では、3点(0.5323772, 3.31338909)(2.11114739, 3.57660449)(1.46870582, 1.86947425)がサポートベクターとして選択されています。また、サポートベクターはマージンの境界線上にのっていることがわかるかと思います。</p>



<h4 class="wp-block-heading jinr-heading d--bold">非線形分類</h4>



<p class="wp-block-paragraph">上記で見てきた分類例では、直線で分類できるような例でした。SVMは、カーネル法と組み合わせることで非線形な分類についても対応することができます。以下のサンプルプログラムを用いて紹介します。</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_gaussian_quantiles
from sklearn.svm import SVC


def show_svm_result(svm_model, ax=None):
    """SVMの結果を表示する

    Args:
        svm_model: SVM学習結果モデル
        ax: axisの指定 (デフォルト: None)
    """
    if ax is None:
        ax = plt.gca()
    n_grid = 50

    xlim, ylim = ax.get_xlim(), ax.get_ylim()
    x = np.linspace(xlim[0], xlim[1], n_grid)
    y = np.linspace(ylim[0], ylim[1], n_grid)
    ygrid, xgrid = np.meshgrid(y, x)
    xygrid = np.vstack([xgrid.ravel(), ygrid.ravel()]).T
    decision = svm_model.decision_function(xygrid).reshape(xgrid.shape)

    # 境界線、マージンを表示
    ax.contour(
        xgrid,
        ygrid,
        decision,
        colors="k",
        levels=[-1, 0, 1],
        linestyles=["--", "-", "--"],
        alpha=0.5,
    )
    # サポートベクターを表示
    ax.scatter(
        svm_model.support_vectors_[:, 0],
        svm_model.support_vectors_[:, 1],
        s=100,
        linewidth=1,
        facecolor="none",
        edgecolor="r",
        label="Support Vector",
    )
    ax.legend()
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)


def main():
    """メイン関数"""
    np.random.seed(0)

    # ===== データの生成
    data, label = make_gaussian_quantiles(n_samples=100, n_classes=2, n_features=2)

    plt.scatter(data[label == 0, 0], data[label == 0, 1], marker="o")
    plt.scatter(data[label == 1, 0], data[label == 1, 1], marker="^")

    # ===== サポートベクターマシンを用いた学習
    model = SVC(C=1.0e10)
    model.fit(data, label)
    print(model)
    print(model.support_vectors_)

    # ===== svmの結果表示
    show_svm_result(model)

    # 描画
    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="">【実行結果】
SVC(C=10000000000.0)
[[-0.74475482 -0.82643854]
 [-0.03928282 -1.1680935 ]
 [-1.10438334  0.05216508]
 [ 0.77179055  0.82350415]
 [ 1.17877957 -0.17992484]
 [ 1.12663592 -1.07993151]
 [-1.14746865 -0.43782004]
 [-1.03424284  0.68159452]
 [-0.51080514 -1.18063218]
 [ 1.18802979  0.31694261]
 [ 0.29823817  1.3263859 ]]</pre>



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


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="636" height="478" src="https://tech.nkhn37.net/wp-content/uploads/2022/08/image-34.png" alt="scikit-learn SVM rbf" class="wp-image-4463" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/08/image-34.png 636w, https://tech.nkhn37.net/wp-content/uploads/2022/08/image-34-300x225.png 300w" sizes="(max-width: 636px) 100vw, 636px" /></figure>
</div>


<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="">from sklearn.datasets import make_gaussian_quantiles</pre>



<p class="wp-block-paragraph">線形では分類できないようなデータ生成用に、sklearn.datasetsからmake_gaussian_quantilesをインポートしています。</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="">    np.random.seed(0)

    # ===== データの生成
    data, label = make_gaussian_quantiles(n_samples=100, n_classes=2, n_features=2)

    plt.scatter(data[label == 0, 0], data[label == 0, 1], marker="o")
    plt.scatter(data[label == 1, 0], data[label == 1, 1], marker="^")</pre>



<p class="wp-block-paragraph"><span style="font-size: 1em; letter-spacing: 0.05em; color: initial;">make_gaussian_quantilesを使用してサンプルデータを作成しています。今回指定しているのは以下のような引数です。値を変えたり、コメントアウトしたりして色々なデータで試してみてください。</span></p>



<ul class="wp-block-list jinr-list">
<li>n_samples：データサンプル数</li>



<li>n_classes：データ集合の数</li>



<li>n_features：データの特徴数</li>
</ul>



<p class="wp-block-paragraph">乱数シードは上記例では、np.random.seedで設定していますが、make_gaussian_quantilesのrandom_state引数で指定することも可能です。</p>



<p class="wp-block-paragraph"><strong>SVC（Support Vector Classification）の実行</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 = SVC(C=1.0e10)
    model.fit(data, label)
    print(model)
    print(model.support_vectors_)</pre>



<p class="wp-block-paragraph">上記の部分がサポートベクターマシンを実行している部分です。今回、<span class="marker"><strong>kernel</strong></span>を指定していませんが、デフォルトの<span class="marker"><strong>rbf</strong></span>（動径基底関数）が指定されています。</p>



<p class="wp-block-paragraph">明示的にkernel=&#8217;rbf&#8217;と指定しても構いません。Cについては、線形分類の説明でも説明した通りマージンの硬さをコントロールするパラメータです。</p>



<p class="wp-block-paragraph"><strong>実行結果の確認</strong><span style="font-size: 1em; letter-spacing: 0.05em; color: initial;"></span></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="">【実行結果（再掲）】
SVC(C=10000000000.0)
[[-0.74475482 -0.82643854]
 [-0.03928282 -1.1680935 ]
 [-1.10438334  0.05216508]
 [ 0.77179055  0.82350415]
 [ 1.17877957 -0.17992484]
 [ 1.12663592 -1.07993151]
 [-1.14746865 -0.43782004]
 [-1.03424284  0.68159452]
 [-0.51080514 -1.18063218]
 [ 1.18802979  0.31694261]
 [ 0.29823817  1.3263859 ]]</pre>



<p class="wp-block-paragraph">【表示結果（再掲）】</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="636" height="478" src="https://tech.nkhn37.net/wp-content/uploads/2022/08/image-34.png" alt="scikit-learn SVM rbf" class="wp-image-4463" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/08/image-34.png 636w, https://tech.nkhn37.net/wp-content/uploads/2022/08/image-34-300x225.png 300w" sizes="(max-width: 636px) 100vw, 636px" /></figure>
</div>


<p class="wp-block-paragraph">結果表示には線形分類の時と同じ独自に作ったshow_svm_result関数を使用しています。結果を見てみると境界面が曲線になっているような分類ができていることが分かります。また、サポートベクターとしては11点が選択されていることが分かるかと思います。</p>



<p class="wp-block-paragraph">この例のように、サポートベクターマシンは非線形な分類についても適用することが可能です。</p>



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



<p class="wp-block-paragraph">本記事では、Pythonの機械学習ライブラリである<span class="marker"><strong>scikit-learn</strong></span>を用いてサポートベクターマシン（SVM）を使ったデータの分類をする方法を紹介してきました。</p>



<p class="wp-block-paragraph">SVM実行のためのコードは、非常に短いコードで実現できていることがお分かりいただけたかと思います。scikit-learnを用いるとSVMのような機械学習の実行が簡単に実現できます。是非色々と試してみていただければと思います。</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.svm.SVC</code> の公式ドキュメントは<a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.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/svm" 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-svm/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:18:29 by W3 Total Cache
-->