前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >浅谈keras中的keras.utils.to_categorical用法

浅谈keras中的keras.utils.to_categorical用法

作者头像
砸漏
发布2020-10-21 10:33:21
2.1K0
发布2020-10-21 10:33:21
举报
文章被收录于专栏:恩蓝脚本

如下所示:

to_categorical(y, num_classes=None, dtype=’float32′)

将整型标签转为onehot。y为int数组,num_classes为标签类别总数,大于max(y)(标签从0开始的)。

返回:如果num_classes=None,返回len(y) * [max(y)+1](维度,m*n表示m行n列矩阵,下同),否则为len(y) * num_classes。说出来显得复杂,请看下面实例。

代码语言:javascript
复制
import keras

ohl=keras.utils.to_categorical([1,3])
# ohl=keras.utils.to_categorical([[1],[3]])
print(ohl)
"""
[[0. 1. 0. 0.]
 [0. 0. 0. 1.]]
"""
ohl=keras.utils.to_categorical([1,3],num_classes=5)
print(ohl)
"""
[[0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]]
"""

该部分keras源码如下:

代码语言:javascript
复制
def to_categorical(y, num_classes=None, dtype='float32'):
  """Converts a class vector (integers) to binary class matrix.

  E.g. for use with categorical_crossentropy.

  # Arguments
    y: class vector to be converted into a matrix
      (integers from 0 to num_classes).
    num_classes: total number of classes.
    dtype: The data type expected by the input, as a string
      (`float32`, `float64`, `int32`...)

  # Returns
    A binary matrix representation of the input. The classes axis
    is placed last.
  """
  y = np.array(y, dtype='int')
  input_shape = y.shape
  if input_shape and input_shape[-1] == 1 and len(input_shape)   1:
    input_shape = tuple(input_shape[:-1])
  y = y.ravel()
  if not num_classes:
    num_classes = np.max(y) + 1
  n = y.shape[0]
  categorical = np.zeros((n, num_classes), dtype=dtype)
  categorical[np.arange(n), y] = 1
  output_shape = input_shape + (num_classes,)
  categorical = np.reshape(categorical, output_shape)
  return categorical

补充知识:keras笔记——keras.utils.to_categoracal()函数

keras.utils.to_categoracal (y, num_classes=None, dtype=’float32′)

将整形标签转为onehot,y为int数组,num_classes为标签类别总数,大于max (y),(标签从0开始的)。

返回:

如果num_classes=None, 返回 len(y)*[max(y)+1] (维度,m*n表示m行n列矩阵),否则为len(y)*num_classes。

以上这篇浅谈keras中的keras.utils.to_categorical用法就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档