Skip to main content
 首页 » 编程设计

python之使用 Theano 逼近 NN 的非线性函数

2024年10月17日5sxdcgaq8080

我使用 Theano 设计了一个神经网络,用于近似数学多重函数。但是我一直无法逼近非线性函数,例如:2x/x+3 等。但是网络在线性函数上表现良好。

我使用 1 个隐藏层和 2 个神经元。我试过增加隐藏层中的神经元。但是,这似乎并不能解决问题。

注意:代码没有任何错误。它也试图最小化成本,但它所做的预测不是预期的(也许它正在学习一些无意义/不需要的模式)。

我使用的(UPDATED-UPDATED)代码是:

x = T.dscalar() 
y = T.dscalar() 
 
inputs = np.random.randint(1,6,size=(500)) 
outputs = (inputs * 2.0) / (inputs + 3.0) 
 
def layer(x, w): 
    b = np.array([1], dtype=theano.config.floatX) 
    x = b * x    # doing to be able to concatenate b and x 
    x = T.concatenate([x, b]) 
    return nnet.sigmoid(T.dot(w.T, x)) 
 
def grad_desc(cost, theta): 
    alpha = 0.01 
    return theta - (alpha * (T.grad(cost, wrt=theta))) 
 
theta1 = theano.shared(np.array(np.random.rand(2,6), dtype=theano.config.floatX)) 
theta2 = theano.shared(np.array(np.random.rand(7,1), dtype=theano.config.floatX)) 
 
h1 = layer(x, theta1) 
h2 = layer(h1, theta2) 
out = T.nnet.softmax(h2) 
fc = T.mean(T.sqr(out - y)) 
 
back_prop = theano.function(inputs=[x,y], outputs=[fc], updates=[ 
                (theta1, grad_desc(fc, theta1)), 
                (theta2, grad_desc(fc, theta2)) 
            ]) 
feed_forward = theano.function(inputs=[x], outputs=[out]) 
 
cur_cost = 0 
for i in range(100): 
    for x, y in zip(inputs, outputs): 
        cur_cost = back_prop(x, y) 
    if i % 10 == 0: 
        print "Epoch ", i/10, " : ", cur_cost 

与 Epoch 相关的成本:

Epoch  0  :  [array(0.0625)] 
Epoch  1  :  [array(0.0625)] 
Epoch  2  :  [array(0.0625)] 
Epoch  3  :  [array(0.0625)] 
Epoch  4  :  [array(0.0625)] 
Epoch  5  :  [array(0.0625)] 
Epoch  6  :  [array(0.0625)] 
Epoch  7  :  [array(0.0625)] 
Epoch  8  :  [array(0.0625)] 
Epoch  9  :  [array(0.0625)] 

测试:

test_values = np.random.randint(1,100, size=(1,6)) 
for i in test_values[0]: 
    print "Result : ", feed_forward(i), "Actual : ", (2.0*i)/(i+3.0) 

测试结果:

Result :  [array([[ 1.]])] Actual :  1.90909090909 
Result :  [array([[ 1.]])] Actual :  1.82857142857 
Result :  [array([[ 1.]])] Actual :  1.66666666667 
Result :  [array([[ 1.]])] Actual :  1.93023255814 
Result :  [array([[ 1.]])] Actual :  1.7 
Result :  [array([[ 1.]])] Actual :  1.85714285714 

感谢任何帮助。

请您参考如下方法:

您的代码不是神经网络……至少在有意义的意义上不是——它只是一个线性模型。当您没有任何非线性激活函数时,拥有隐藏层毫无意义,因为您可以建模的一切都只是输入的线性函数。添加非线性,添加它们各自的梯度,然后您将能够对非线性函数进行建模。