gpt4 book ai didi

python - 西亚诺 'Expected an array-like object, but found a Variable' : Using scan & categorical_crossentropy

转载 作者:行者123 更新时间:2023-11-30 09:19:59 24 4
gpt4 key购买 nike

我正在尝试对 theano 中的多重损失求和,但我无法使其工作。我正在使用分类交叉熵。

这是我的代码:

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?

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

最佳答案

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

loss = loss_cal(answers, predictions)

这是错误的,因为预测是 theano 矩阵,我应该使用 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)
无论如何,谢谢

关于python - 西亚诺 'Expected an array-like object, but found a Variable' : Using scan & categorical_crossentropy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43414306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com