OneHotEncode仅对整数、片(`:`)、省略号(`…`)、numpy.newaxis(`None`)和整数或布尔数组进行编码存在有效标识问题

2024-05-20 01:06:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过一个热编码来解决以下问题,但也出现了错误

我正在尝试进行图像分类(捕捉矩形),当我尝试让它进行一次热编码时,出现了错误。 在更改为一个热标签之前,
标签如下:

 'circle' 'circle' 'circle' 'circle' 'circle' 'circle' 'circle' 'circle'
 'pentagon' 'pentagon' 'pentagon' 'pentagon' 'pentagon' 'rectangle' ....
 'triangle' 'triangle' 'triangle' 'triangle' 'triangle' 'triangle']

我把T变成了[[0, 0, 0, 0, 0], ... , [0, 0, 0, 0, 0]],因为我有5种图形。 但是在row[X[idx]] = 1

我得到了一个错误: only integers, slices (), ellipsis (), numpy.newaxis () and integer or boolean arrays are valid indices

def _change_one_hot_label(X):
    T = np.zeros((X.size, 5))
    for idx, row in enumerate(T):
        if(X[idx] == 'rectangle'):
            row[X[idx]] = 1

    return T

我不知道该怎么解决这个问题

请帮帮我。谢谢

======================================================================================================

试图用上述方法解决。(一次热编码)

==================================================================================
我在学习深度学习

我收到一个错误:“ufunc”multiply”不包含具有签名匹配类型(dtype('dtype')的循环

我试图自己解决,但我需要帮助

我正在加载图像数据集

data_list = glob('dataset\\training\\*\\*.jpg')

def load_label(data_list):
    labels = []
    for path in data_list:
        labels.append(get_label_from_path(path))
    return np.array(labels)

x_批次示例:[[0.00392157 0.00392157 0.00392157…0.00392157 0.00392157 0.00392157 0.00392157] ... [0.00392157 0.00392157 0.00392157 ... 0.00392157 0.00392157 0.00392157]]
t_批次示例:[“圆”“圆”…“圆”“圆”]

train_size = 3 # x_train.shape[0]
batch_size = 22
for i in range(242): # iters_num = 242
   batch_mask = np.random.choice(train_size, batch_size)
   print( t_train, batch_mask )
   x_batch = x_train[batch_mask]
   t_batch = t_label[batch_mask]
   grad = network.gradient(x_batch, t_batch) # error start position

当我尝试获得梯度时,它流动self.loss(x_batch, t_batch) # each parameter is x, t->

def loss(self, x, t):
        y = self.predict(x)
        return self.lastLayer.forward(y, t)

def forward(self, x, t):
        self.t = t
        self.y = softmax(x)
        self.loss = cross_entropy_error(self.y, self.t)
        return self.loss

def cross_entropy_error(y, t): 
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)

    batch_size = y.shape[0]

    return -np.sum(t * np.log(y+1e-7)) / batch_size

最新一行,return -np.sum(t*np.log(y+1e-7)) / batch_size
我得到一个错误:UFuncTypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')

我尝试将标签更改为int,例如:“圆”=0,“矩形”=1,但我的深入学习并没有了解到这一点

我不知道我错过了什么。。 谁能帮帮我吗


Tags: selfsizereturndef错误npbatchtrain
1条回答
网友
1楼 · 发布于 2024-05-20 01:06:34

要解决一个热编码问题,可以使用以下函数

import numpy as np

label2idx = dict(rectangle=0, circle=1, pentagon=2, ..)

def _change_one_hot_label(X):
    T = np.zeros((len(X), 5)).astype('int32')
    for i in range(T.shape[0]):
        label = X[i]
        T[i, label2idx[label]] = 1

    return T

_change_one_hot_label(['circle', 'rectangle', 'rectangle'])

对于另一个问题,正如您所说,变量t是一个包含['circle', 'rect' ..]的字符串数组,不能将字符串和数字相乘

首先,您应该对t应用一个热编码函数

def cross_entropy_error(y, t): 
    # It is nota good practice, but you can place this instruction here
    # Maybe, if you have a 'batch preprocessor function' you should place it there
    t = _change_one_hot_label(t)

    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)

    batch_size = y.shape[0]
    return -np.sum(t * np.log(y+1e-7)) / batch_size

相关问题 更多 >