<?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>「tf.keras.utils.to_categorical」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/tf-keras-utils-to_categorical/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 11 Jan 2026 05:57:06 +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>「tf.keras.utils.to_categorical」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【TensorFlow】one-hotエンコーディングの方法</title>
		<link>https://tech.nkhn37.net/tensorflow-one-hot-encoding/</link>
					<comments>https://tech.nkhn37.net/tensorflow-one-hot-encoding/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Wed, 19 Oct 2022 20:00:00 +0000</pubDate>
				<category><![CDATA[TensorFlow]]></category>
		<category><![CDATA[one-hotエンコーディング]]></category>
		<category><![CDATA[one-hotベクトル]]></category>
		<category><![CDATA[tf.keras.utils.to_categorical]]></category>
		<category><![CDATA[tf.one_hot]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=5248</guid>

					<description><![CDATA[Googleによって開発されている機械学習ライブラリであるTensorFlowで、one-hotエンコーディングをする方法について解説します。 one-hotエンコーディングとは one-hotエンコーディングとは、ある [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Googleによって開発されている機械学習ライブラリであるTensorFlowで、<span class="marker"><strong>one-hotエンコーディングをする方法</strong></span>について解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">one-hotエンコーディングとは</h2>



<p class="wp-block-paragraph"><span class="marker"><strong>one-hotエンコーディング</strong></span>とは、ある次元のベクトルのうち1つだけが1で、他については全て0になるような表現に変換することを言います。変換されたベクトルは<span class="marker"><strong>one-hot表現</strong></span>、<span class="marker"><strong>one-hotベクトル</strong></span>といったように呼びます。</p>



<p class="wp-block-paragraph">文章だといまいち分かりづらいかもしれませんので、以下の図で一例を見てみましょう。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="583" src="https://tech.nkhn37.net/wp-content/uploads/2022/10/image-1-1024x583.png" alt="one-hotエンコーディング (ベクトル, 表現)" class="wp-image-5268" style="aspect-ratio:1.7564676918109536;width:608px;height:auto" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/10/image-1-1024x583.png 1024w, https://tech.nkhn37.net/wp-content/uploads/2022/10/image-1-300x171.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/10/image-1-768x437.png 768w, https://tech.nkhn37.net/wp-content/uploads/2022/10/image-1.png 1119w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">上記例では、データがdata1~data5までの5つあり、それぞれにラベルが設定されている状況だと思ってください。データは、例えば画像や音声等、ラベルはそのデータの分類というようなイメージを持ってもらうと分かりやすいかと思います。このラベルをone-hotエンコーディングすることを考えてみます。</p>



<p class="wp-block-paragraph">図の右側がラベルについてone-hotエンコーディングをした結果です。ベクトルの各列がそれぞれのラベルを意味しています。例えば、data1のラベルは2なので、2に該当する列のみ「1」で、他の列は「0」となる[0, 0, 1, 0]というone-hotベクトルとなります。1つだけ値があるという意味で「one-hot」といういうわけです。</p>



<p class="wp-block-paragraph">ディープラーニングなどの機械学習では、こういったone-hotベクトルに変換して学習に使用することがよくあり、TensorFlowではone-hotエンコーディングをするための方法がいくつか用意されています。</p>



<p class="wp-block-paragraph">以降では、TensorFlowでone-hotエンコーディングする方法について紹介します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">tf.one_hotを使用してone-hotエンコーディングする</h3>



<h4 class="wp-block-heading jinr-heading d--bold">基本的な使い方</h4>



<p class="wp-block-paragraph">TensorFlowでone-hotエンコーディングする際には、以下のように<span class="marker"><strong>tf.one_hot</strong></span>が使用できます。</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 tensorflow as tf

labels = tf.constant([2, 1, 3, 1, 0])
depth = 5

# one-hotエンコーディング tf.one_hot
one_hot_tensor = tf.one_hot(labels, depth)
print(one_hot_tensor)</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="">【実行結果】
tf.Tensor(
[[0. 0. 1. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 1. 0. 0. 0.]
 [1. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32)</pre>



<p class="wp-block-paragraph">labelsがエンコーディング対象のリストです。<span class="marker"><strong>depth</strong></span>は、データのクラス数(ラベル数)に該当する数値です。結果の各行を見てみると確かにラベルの数値に該当する位置が1となっているone-hotベクトルとなっていることが分かるかと思います。</p>



<p class="wp-block-paragraph">今回はラベルの数としては[0, 1, 2, 3]の4種類ですが、depth=5で指定していますので「4」もクラスとしてはある想定での変換になっています。そのため、いずれのone-hotエンコーディング結果でも4に該当する5列目は全て0になっていることが分かります。</p>



<p class="wp-block-paragraph">このdepth引数は、指定をしない場合はエラーになるので注意してください。</p>



<h4 class="wp-block-heading jinr-heading d--bold">depthがデータのクラス数より少ない場合</h4>



<p class="wp-block-paragraph">depthの指定がデータのクラス数(ラベル数)より少ない場合には、どのような結果となるかを以下の例で見ておきましょう。</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 tensorflow as tf

labels = tf.constant([2, 1, 3, 1, 0])
depth = 3

# one-hotエンコーディング tf.one_hot
# (depthがデータのクラス数より少ない場合)
one_hot_tensor = tf.one_hot(labels, depth)
print(one_hot_tensor)</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="">【実行結果】
tf.Tensor(
[[0. 0. 1.]
 [0. 1. 0.]
 [0. 0. 0.]
 [0. 1. 0.]
 [1. 0. 0.]], shape=(5, 3), dtype=float32)</pre>



<p class="wp-block-paragraph">上記では、ラベルの数としては[0, 1, 2, 3]の4種類ですがdepth=3として指定してます。この場合、ラベル3に該当するone-hotベクトルでは、1にする列がないことになりますので結果は[0, 0, 0]となります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">on_value, off_valueによる値の指定</h4>



<p class="wp-block-paragraph">tf.one_hotの引数として、<span class="marker"><strong>on_value</strong></span>と<span class="marker"><strong>off_value</strong></span>という引数があります。on_valueは、デフォルトの際で1が入る場所の数値を指定することができます。一方、off_valueは、0が入る場所の数値を指定することができます。</p>



<p class="wp-block-paragraph">以下の例は、on_value=5.0、off_value=-1.0を指定した場合です。</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 tensorflow as tf

labels = tf.constant([2, 1, 3, 1, 0])
depth = 5

# one-hotエンコーディング tf.one_hot
# (on_value, off_valueの指定)
one_hot_tensor = tf.one_hot(labels, depth, on_value=5.0, off_value=-1.0)
print(one_hot_tensor)</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="">【実行結果】
tf.Tensor(
[[-1. -1.  5. -1. -1.]
 [-1.  5. -1. -1. -1.]
 [-1. -1. -1.  5. -1.]
 [-1.  5. -1. -1. -1.]
 [ 5. -1. -1. -1. -1.]], shape=(5, 5), dtype=float32)</pre>



<p class="wp-block-paragraph">結果を見てみると、引数を指定しない時に1が設定された部分に「5.」、0が設定された場所に「-1.」が設定されることが分かるかと思います。on_value、off_valueは意図して値を指定したい場合に使用することができます。</p>



<h3 class="wp-block-heading jinr-heading d--bold">tf.keras.utils.to_categoricalを使用してone-hotエンコーディングする</h3>



<h4 class="wp-block-heading jinr-heading d--bold">基本的な使い方</h4>



<p class="wp-block-paragraph">TensorFlowの高水準APIであるKerasの<span class="marker"><strong>tf.keras.utils.to_categorical</strong></span>を以下のように使用することでもone-hotエンコーディングをすることが可能です。</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 tensorflow as tf

labels = tf.constant([2, 1, 3, 1, 0])

# one-hotエンコーディング tf.keras.utils.to_categorical
one_hot_array = tf.keras.utils.to_categorical(labels)
print(one_hot_array)
print(type(one_hot_array))</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="">【実行結果】
[[0. 0. 1. 0.]
 [0. 1. 0. 0.]
 [0. 0. 0. 1.]
 [0. 1. 0. 0.]
 [1. 0. 0. 0.]]
&lt;class 'numpy.ndarray'></pre>



<p class="wp-block-paragraph">結果を見てみるとone-hotベクトルに変換できていることが分かります。tf.one_hotでは、クラス数に該当するdepthの指定が必要でしたが、tf.keras.utils.to_categoricalでは必要なく、含まれるデータから適切なサイズでone-hot表現を作成してくれます。</p>



<p class="wp-block-paragraph">なお、返却値はNumPyの配列であるndarrayになります。また、tf.one_hotのようにon_value, off_valueの値を設定することはできません。</p>



<h4 class="wp-block-heading jinr-heading d--bold">num_classesによるクラス数の指定</h4>



<p class="wp-block-paragraph">エンコーディングのクラス数(ラベル数)を指定する方法として、<span class="marker"><strong>num_classes</strong></span>を使用することができます。tf.one_hotにおけるdepthに該当します。</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 tensorflow as tf

labels = tf.constant([2, 1, 3, 1, 0])
num_class = 5

# one-hotエンコーディング tf.keras.utils.to_categorical
# (num_classesによるクラス数の指定)
one_hot_array = tf.keras.utils.to_categorical(labels, num_classes=num_class)
print(one_hot_array)
print(type(one_hot_array))</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="">【実行結果】
[[0. 0. 1. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 1. 0. 0. 0.]
 [1. 0. 0. 0. 0.]]
&lt;class 'numpy.ndarray'></pre>



<p class="wp-block-paragraph">ラベルの数としては[0, 1, 2, 3]の4種類ですが、num_classes=5で指定していますので「4」もクラスとしてはある想定での変換になっています。そのため、いずれのone-hotエンコーディング結果でも4に該当する5列目は全て0になっていることが分かります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">num_classesがデータのクラス数より少ない場合</h4>



<p class="wp-block-paragraph">num_classesの指定がデータのクラス数(ラベル数)より少ない場合には、どのような結果となるかを以下の例で見ておきましょう。</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 tensorflow as tf

labels = tf.constant([2, 1, 3, 1, 0])
num_class = 3

# one-hotエンコーディング tf.keras.utils.to_categorical
# (num_classesによるクラス数の指定でデータのクラス数より少ない場合)
one_hot_array = tf.keras.utils.to_categorical(labels, num_classes=num_class)
print(one_hot_array)
print(type(one_hot_array))</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="">【実行結果】
IndexError: index 3 is out of bounds for axis 1 with size 3</pre>



<p class="wp-block-paragraph">この場合、tf.keras.utils.to_categoricalでは処理途中でエラーとなります。tf.one_hotでは足りない列の部分が無視された点と挙動が少し異なりますので覚えておきましょう。</p>



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



<p class="wp-block-paragraph">Googleによって開発されている機械学習ライブラリであるTensorFlowで、<span class="marker"><strong>one-hotエンコーディングをする方法</strong></span>について解説しました。</p>



<p class="wp-block-paragraph">one-hotエンコーディングする方法としては、<span class="marker"><strong>tf.one_hot</strong></span>とKerasに実装されている<span class="marker"><strong>tf.keras.utils.to_categorical</strong></span>を使用することができます。上記で紹介したように指定できる引数や挙動に少し違いがありますので注意しましょう。</p>



<p class="wp-block-paragraph">ディープラーニングの実装としてTensorFlowを勉強するとKerasを使用した実装が多いですので、tf.keras.utils.to_categoricalを目にする方が多いのではないかなという印象です。機能としてはtf.one_hotの方が、on_valueやoff_valueの指定ができるなどより扱える幅が少し柔軟かなと思います。</p>



<p class="wp-block-paragraph">one-hotエンコーディングは、機械学習でよく出てくる表現方法ですので、変換方法についてしっかり覚えておくとよいでしょう。</p>



<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/tensorflow/fundamentals/one-hot-encoding" 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/tensorflow-one-hot-encoding/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 22:55:23 by W3 Total Cache
-->