Theano“预期了类似数组的对象,但找到了一个变量":使用scan& categorical_crossentropy [英] Theano 'Expected an array-like object, but found a Variable': Using scan & categorical_crossentropy

查看:87
本文介绍了Theano“预期了类似数组的对象,但找到了一个变量":使用scan& categorical_crossentropy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试总结theano的多次损失,但我无法使其工作. 我正在使用绝对交叉熵.

I'm trying to sum multiple loss in theano but I can't make it work. I'm using the categorical crossentroy.

这是我的代码:

import numpy as np

import theano
import theano.tensor as T


answers = T.ivector()
temp = T.scalar()
predictions = T.matrix()

def loss_acc(curr_ans,curr_pred, loss):
    temp= T.nnet.categorical_crossentropy(curr_pred.dimshuffle('x',0), T.stack([curr_ans]))[0]
    return temp + loss



outputs, updates = theano.scan(fn = loss_acc, 
                               sequences = [answers, predictions], 
                               outputs_info = [np.float64(0.0)], 
                                               n_steps = 5)

loss = outputs[-1]

loss_cal = theano.function(inputs = [answers, predictions], outputs = [loss])

#Here I'm just generating some random data to see if I can make the code work
max_nbr = 5
pred = []
for i in range(0, max_nbr):
    temp = np.ones(8)
    temp[i] = temp[i] + 5
    temp = temp/sum(temp)
    pred.append(temp)


answers = []
for i in range(0, max_nbr):
    answers.append(pred[i].argmax())

loss = loss_cal(answers, predictions)
print(loss)

我得到的错误是

Expected an array-like object, but found a Variable:
TypeError: ('Bad input argument to theano function with name "main.py:89" at index1(0-based)', Expected an array-like object but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?

我不明白为什么我的代码不起作用,有人可以向我解释吗?非常感谢!

I don't get why my code doesn't work, can someone explain it to me? Thanks a lot!

推荐答案

我发现了我的问题,这确实是一个愚蠢的问题.

I found my problem, it's really a stupid one.

loss = loss_cal(answers, predictions)

这是错误的,因为预测是theano矩阵,所以我应该一直使用pred.

This is wrong, as predictions is the theano matrix, I should have been using pred.

pred = []
for i in range(0, max_nbr):
    temp = np.ones(8)
    temp[i] = temp[i] + 5
    temp = temp/sum(temp)
    pred.append(temp)

现在可以与 loss = loss_cal(answers, pred) 仍然感谢

It works now with loss = loss_cal(answers, pred) Thanks anyway

这篇关于Theano“预期了类似数组的对象,但找到了一个变量":使用scan& categorical_crossentropy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆