TensorFlow tf.one_hot( )剖析

1. 首先解释one_hot encoding(独热编码)

one_hot encoding可作为机器学习中对离散型特征的一种处理手段,一般用于处理监督学习中分类问题样本的标注数据。例如有三类特征{label1,label2,label3},需要三个bit位实现编码,bit位为1的位置对应原来的特征值,即上述特征对应的编码为{100, 010, 001}。

2.tf.one_hot( label_batch,  class_num )

tf.one_hot( ) 函数原型为:

one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)

indices: 代表了on_value所在的索引,其他位置值为off_value。类型为tensor,其尺寸与depth共同决定输出tensor的尺寸。

depth:编码深度。

on_value & off_value为编码开闭值,缺省分别为1和0,indices指定的索引处为on_value值;

axis:编码的轴,分情况可取-1、0或-1、0、1,默认为-1

dtype:默认为 on_value 或 off_value的类型,若未提供on_value或off_value,则默认为tf.float32类型。

返回一个 one-hot tensor。

2. 应用

(1) indices是一个标量, 输出是一个长度为‘depth’的向量;

(2) indices是一个长度为features的向量,输出尺寸为:(a) 当axis==-1,features*depth  (b) 当axis==0,depth*features

(3) indices是一个尺寸为[batch,features]的矩阵,输出尺寸为:

    (a) 当axis==-1,batch*features*depth (b)当axis==1,batch*depth*features (c)当axis==0,depth*batch*features

第(2)种情况举例:

   ```python
      indices = [0, 2, -1, 1]
      depth = 3
      on_value = 5.0
      off_value = 0.0
      axis = -1

    ```

输出尺寸为4*3, ```python
                          output =
                          [5.0 0.0 0.0]  // one_hot(0)
                          [0.0 0.0 5.0]  // one_hot(2)
                          [0.0 0.0 0.0]  // one_hot(-1)
                          [0.0 5.0 0.0]  // one_hot(1)

                          ```

第(3)种情况举例:

   ```python
      indices = [[0, 2], [1, -1]]
      depth = 3
      on_value = 1.0
      off_value = 0.0
      axis = -1

    ```

输出尺寸为:2*2*3,结果:```python
                                          output =
                                          [
                                            [1.0, 0.0, 0.0]  // one_hot(0)
                                            [0.0, 0.0, 1.0]  // one_hot(2)
                                          ][
                                            [0.0, 1.0, 0.0]  // one_hot(1)
                                            [0.0, 0.0, 0.0]  // one_hot(-1)
                                          ]

                                        ```

3. 分类代码中标注数据的处理:

onehot_label_batch = tf.one_hot(label_batch, class_num)

对标签(label)数据使用one-hot vectors,label n(数字)表示成只有第n维度数字为1的class_num维向量,n为0,1...class_num-1。若有5类,class_num = 5, 标签0表示为[1, 0, 0, 0, 0],标签1表示为[0, 1, 0, 0, 0],以此类推。

import numpy as np import tensorflow as tf from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist from keras import backend as K from keras.optimizers import Adam import skfuzzy as fuzz import pandas as pd from sklearn.model_selection import train_test_split # 绘制损失曲线 import matplotlib.pyplot as plt import time from sklearn.metrics import accuracy_score data = pd.read_excel(r"D:\pythonProject60\filtered_data1.xlsx") # 读取数据文件 # Split data into input and output variables X = data.iloc[:, :-1].values y = data.iloc[:, -1].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 导入MNIST数据集 # 数据预处理 y_train = np_utils.to_categorical(y_train, 3) y_test = np_utils.to_categorical(y_test, 3) # 创建DNFN模型 start_time=time.time() model = Sequential() model.add(Dense(64, input_shape=(11,), activation='relu')) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(3, activation='softmax')) # 编译模型 model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy']) # 训练模型 history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128) # 使用DNFN模型进行预测 y_pred = model.predict(X_test) y_pred= np.argmax(y_pred, axis=1) print(y_pred) # 计算模糊分类 fuzzy_pred = [] for i in range(len(y_pred)): fuzzy_class = np.zeros((3,)) fuzzy_class[y_pred[i]] = 1.0 fuzzy_pred.append(fuzzy_class) fuzzy_pred = np.array(fuzzy_pred) end_time = time.time() print("Total time taken: ", end_time - start_time, "seconds")获得结果并分析
05-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值