我使用scipy.optimize.fsolve
函数,代码如下:
我试图求解obj函数的值x_1
,保持x_2
的值不变。应当注意,x_1
和x_2
的值在0和1之间。我将w_xx
、b_xx
和y_test
的值相加。
import numpy as np
from scipy.optimize import fsolve
y_test = np.array([3.448 ,11.071,3.602 ,11.838,3.512 ,13.78,4.013,15.209,3.339,13.15,3.387,17.419,3.793,15.303,3.92,11.683,3.655 ,14.317]).reshape(9,2)
#weight matrix
w_01 = np.array([0.5524624,0.72511494,0.51372594,-0.6308459]).reshape(2,2)
w_T2 = np.array([[-0.59752214, -0.5804831, 1.4108963, -0.2634158, -0.5614638, -1.0390981, 0.65243214, 0.7106961, -0.5652963, -0.0601576, 0.90772694, -1.3798463, -0.40833127, -0.7003734, -0.21786042, 0.27037245]]).reshape(2,8)
w_02 = np.transpose(w_T2)
w_03 = np.array([[-1.0097426,0.32732514,0.24015452,-1.0950012,0.24607354,-0.21128657,-0.89929247,0.5828309,-1.4573368,-1.0770408,0.62045175,-1.2865094,-1.3986484,-1.2846812, 0.9638692 ,1.5144163]]).reshape(2,8)
#Bais matrix
b_01 = np.array([0.859291,0.59829414]).reshape(2,1)
b_02 = np.array([-0.5619188,-0.57078356,0.5717453,-0.5602762,-0.61745477,-0.6130685,0.56874627,0.55697656]).reshape(8,1)
b_03 = np.array([0.23421602,0.48550755]).reshape(2,1)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
### Defining Obj function
### inp is 2x1 matrix and out is also 2x1 matrix
def objfunction(x1,x2,y):
inp = np.array([x1,x2]).reshape(2,1)
out = y.reshape(2,1)
f = (np.dot(w_03,(np.dot(w_02,(sigmoid(np.dot(w_01,inp) + b_01))) + b_02)) + b_03) - out # value of y
return f.flatten()
### Calculating Solution
x_1 = 0 ### Inital guess
x_2 = 0.5
sol = np.zeros((len(y_test),2))
for i,value in enumerate(y_test):
sol[i] = fsolve(objfunction,x_1,args=(x_2,value))
字符串
错误代码:
p:\python\mimo_fsolve.py:46: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
inp = np.array([x1,x2]).reshape(2,1)
AttributeError: 'numpy.ndarray' object has no attribute 'exp'
loop of ufunc does not support argument 0 of type numpy.ndarray which has no callable exp method
型
1条答案
按热度按时间t30tvxxf1#
为了回答你的主要问题,你得到这个错误的原因是因为
fsolve
为objfunction
提供了一个看起来像x1
的np.array([x1])
的numpy数组。当您尝试将其与x2
(浮点型)组合以生成inp
时,会创建一个不规则的数组,因为第一个元素是数组,第二个元素只是一个数字。Numpy不喜欢这样,所以它将数组转换为object
数据类型。如果你尝试下面的代码,你可以看到这一点:字符串
当您尝试在对象数组上执行
np.exp
时(因为inp
是对象数据类型,np.dot(w_01, inp) + b_01
也将是),numpy会抛出错误,因为在对象数组上没有np.exp
的实现(重读错误,您会看到这就是错误的内容)。要解决这个问题,可以将
inp
定义中的x1
替换为x1[0]
。但是你最终会遇到另一个问题,因为你返回的是f.flatten()
,它的形状是(2,)
,因为它包含x2
,而fsolve
期望返回的是(1,)
,因为这是它给出的函数。您可以通过获取第一个元素(即f.flatten()[0]
)。最后一个问题是,您将sol
定义为(n,2)
,但您似乎只想存储x_1
,因此只需将其设置为1D数组。型