TypeError:无法转换numpy.str类型的np.ndarray。唯一受支持的类型是:float64、float32

2024-04-25 01:02:56 发布

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

我正在使用RNN算法来预测用户的下一个位置,并使用torch对其进行训练,但我得到了这个错误

我得到了这个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

--> 203         total_loss += run(batch_user, batch_td, batch_ld, batch_loc, batch_dst, step=1)


<ipython-input-34-3a623cd33ef9> in run(user, td, ld, loc, dst, step)

--> 159     user = Variable(torch.from_numpy(np.asarray([user],dtype='<U32'))).type(ltype)

TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.

我的代码是:

###############################################################################################
def run(user, td, ld, loc, dst, step):

    optimizer.zero_grad()

    seqlen = len(td)

    user = Variable(torch.from_numpy(np.asarray([user],dtype='<U32'))).type(ltype)

    #neg_loc = Variable(torch.FloatTensor(1).uniform_(0, len(poi2pos)-1).long()).type(ltype)
    #(neg_lati, neg_longi) = poi2pos.get(neg_loc.data.cpu().numpy()[0])
    rnn_output = h_0
    for idx in xrange(seqlen-1):
        td_upper = Variable(torch.from_numpy(np.asarray(up_time-td[idx],dtype='<U32'))).type(ftype)
        td_lower = Variable(torch.from_numpy(np.asarray(td[idx]-lw_time,dtype='<U32'))).type(ftype)
        ld_upper = Variable(torch.from_numpy(np.asarray(up_dist-ld[idx],dtype='<U32'))).type(ftype)
        ld_lower = Variable(torch.from_numpy(np.asarray(ld[idx]-lw_dist,dtype='<U32'))).type(ftype)
        location = Variable(torch.from_numpy(np.asarray(loc[idx],dtype='<U32'))).type(ltype)
        rnn_output = strnn_model(td_upper, td_lower, ld_upper, ld_lower, location, rnn_output)#, neg_lati, neg_longi, neg_loc, step)

Tags: fromnumpytypenptorchvariableloctd
1条回答
网友
1楼 · 发布于 2024-04-25 01:02:56

可能该用户属于object类型。 因此,尝试使用类似于user.dtype(“category”).cat.code的代码将其转换为数字

相关问题 更多 >