gpt4 book ai didi

theano - theano 函数的错误输入参数

转载 作者:行者123 更新时间:2023-12-01 11:33:10 28 4
gpt4 key购买 nike

我是theano的新手。我正在尝试实现简单的线性回归,但我的程序抛出以下错误:

TypeError: ('Bad input argument to theano function with name "/home/akhan/Theano-Project/uog/theano_application/linear_regression.py:36" at index 0(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?')

这是我的代码:

import theano
from theano import tensor as T
import numpy as np
import matplotlib.pyplot as plt

x_points=np.zeros((9,3),float)
x_points[:,0] = 1
x_points[:,1] = np.arange(1,10,1)
x_points[:,2] = np.arange(1,10,1)
y_points = np.arange(3,30,3) + 1


X = T.vector('X')
Y = T.scalar('Y')

W = theano.shared(
value=np.zeros(
(3,1),
dtype=theano.config.floatX
),
name='W',
borrow=True
)

out = T.dot(X, W)
predict = theano.function(inputs=[X], outputs=out)

y = predict(X) # y = T.dot(X, W) work fine

cost = T.mean(T.sqr(y-Y))

gradient=T.grad(cost=cost,wrt=W)

updates = [[W,W-gradient*0.01]]

train = theano.function(inputs=[X,Y], outputs=cost, updates=updates, allow_input_downcast=True)


for i in np.arange(x_points.shape[0]):
print "iteration" + str(i)
train(x_points[i,:],y_points[i])

sample = np.arange(x_points.shape[0])+1
y_p = np.dot(x_points,W.get_value())
plt.plot(sample,y_p,'r-',sample,y_points,'ro')
plt.show()

此错误背后的解释是什么? (没有从错误消息中得到)。提前致谢。

最佳答案

Theano 在定义计算图和使用此类图计算结果的函数之间有一个重要区别。

当你定义

out = T.dot(X, W)
predict = theano.function(inputs=[X], outputs=out)

您首先为 out 设置计算图在 X 方面和 W .注意 X是一个纯符号变量,它没有任何值,但是 out 的定义告诉 Theano,“给定 X 的值,这就是计算 out 的方法”。

另一方面,predicttheano.function它采用 out 的计算图和 X 的实际数值产生一个数字输出。你传递给 theano.function 的内容当你调用它时,它总是必须有一个实际的数值。所以这样做根本没有意义

y = predict(X)

因为X是符号变量,没有实际值。

您要这样做的原因是您可以使用 y进一步构建您的计算图。但是没有必要使用predict为此:predict 的计算图已在变量 out 中可用定义较早。所以你可以简单地删除定义 y 的行完全然后将您的成本定义为

cost = T.mean(T.sqr(out - Y))

其余代码将不加修改地工作。

关于theano - theano 函数的错误输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30473429/

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