naddary一维数组使用reshape设置为一位数组后无法使用@运算符

def get_Xy(df):#读取特征
#     """
#     use concat to add intersect feature to avoid side effect
#     not efficient for big dataset though
#     """
    ones = pd.DataFrame({'ones': np.ones(len(df))})#ones是m行1列的dataframe
    data = pd.concat([ones, df], axis=1# 合并数据,根据列合并 axis = 1的时候,concat就是行对齐,然后将不同列名称的两张表合并 加列
    X = data.iloc[:, :-1# 这个操作返回 ndarray,不是矩阵
    X= X.values
    y = data.iloc[:, -1]
    y = y.values.reshape(len(y),1)
    return X,y

X, y = get_Xy(data)

def sigmoid(z):
    gz = 1/(1+np.exp(-z))
    return gz

theta = np.zeros([3,1]) 
theta

def computeCost(theta, X, y):
    ''' cost fn is -l(theta) for you to minimize'''
    # your code here  (appro ~ 2 lines)
    #theta = theta.reshape(3,1)
    #y = y.reshape(100,1)
    first = y*np.log(sigmoid(X@theta))
    second = (1-y)*np.log(1 - sigmoid(X@theta))
    costf = -np.sum(first+second) / (len(X)) 
    return costf
computeCost(theta, X, y)

def gradient(theta, X, y):
    # your code here  (appro ~ 2 lines)
    return X.T@(sigmoid(X@theta)-y)/len(X)

print(gradient(theta, X, y))

def gradientdescent(theta, X, y,alpha,iters):
    theta = theta.reshape(3,1)
    y = y.reshape(100,1)
    temp = np.zeros(theta.shape)
    for i in range(iters):
        temp = theta -(alpha/len(X))*X.T@(sigmoid(X@theta)-y)
        theta = temp
        cost = computeCost(theta, X, y)
    return theta, cost

alpha = 0.003
iters = 200000
g, cost= gradientdescent(theta, X, y,alpha,iters)
print(g, '\n',cost)

import scipy.optimize as opt
res = opt.minimize(fun=computeCost, x0=theta, args=(X, y),method='Newton-CG', jac=gradient)
#在这里开始就会报错说The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Numpy对逻辑表达式判别不清楚
print(res)

就是以上代码因为使用.shape函数可以看到我的y是(3,1)但是如果我没用reshape去更改的话默认是(3,)但类型都是naddary,theta也是一样,问题就是我如果不做.reshape处理的话会在前面的梯度下降跟cost函数那里报错除非不使用@这个运算符但换成.T来计算的话输出结果又不对,但如果使用.reshape来提前处理保持全部参数维度一致的话最后这里会报错The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(),请问是为什么,有什么解决办法吗,我目前只能够在函数里面单独处理要调用的参数当做局部变量保持维度一致,一旦在函数外面当做全局变量设置维度一致的话就会出问题
theta = np.zeros([3,1]) # 你这个是不是有问题?

应该是

theta = np.zeros((3,1))

不是的话,给部分data数据

两种写法都可以...

我还真没见过【doge】

而且我这边theta打印就是(3, 1)


你的梯度下降函数计算有问题,返回值符合jac的格式要求



def gradient(theta, X, y):
    # your code here  (appro ~ 2 lines)
    return X.T@(sigmoid(X@theta)-y)/len(X) # 你这里是多层的

#比如随便改一个格式
return np.array([-1, 2, 3]) # 必须是单层的



源码的话在_minimize的535; 你自己也打印了gradient的结果(多层的),和jac要求的输入格式不符

你的梯度下降函数计算有问题,返回值不符合jac的格式要求

https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html这里有多种梯度下降计算方式


def gradient(theta, X, y):
    # your code here  (appro ~ 2 lines)
    tmp =  X.T@(sigmoid(X@theta)-y)/len(X)

    return np.array([item[0] for item in tmp]) # 如果每列是一组数据的话


我把这里y = y.values.reshape(len(y),1)改成
y = y.values

def gradientdescent(theta, X, y,alpha,iters):
    #theta = theta.reshape(3,1)
    #y = y.reshape(100,1)
    temp = np.zeros(theta.shape)
    for i in range(iters):
        temp = theta -(alpha/len(X))*X.T@(sigmoid(X@theta)-y)
        theta = temp
        cost = computeCost(theta, X, y)
    return theta, cost

alpha = 0.003
iters = 200000
g, cost= gradientdescent(theta, X, y,alpha,iters)
print(g, '\n',cost)
#这两句注释掉程序就正常运行了,感觉问题出在y和theta的维度上,但是为什么会这样啊,还有我想问下theta -(alpha/len(X))*X.T@(sigmoid(X@theta)-y)这句话后半段是根据损失函数求导得出的一个梯度函数这样一个方向函数并在这个方向函数上乘以学习速率来进行下降但为什么前半段要用theta减去这个下降的值呢
def find_decision_boundary(density, power, theta, threshhold):
    t1 = np.linspace(-1, 1.5, density)
    t2 = np.linspace(-1, 1.5, density)   #会产生一个2.5*2.5的方形


    cordinates = [(x, y) for x in t1 for y in t2]   #让x,y在处理后的t1 t2 中取值组成点
    x_cord, y_cord = zip(*cordinates) #组合成点在方形里面找了1000^2个点
    mapped_cord = feature_mapping(x_cord, y_cord, power)  # 使用前面的映射函数把去来的点映射成28维的相当于一个一百万行的矩阵
                                                          #每行有28个数而这28个数相当于x1x2,x1x2^2......x2^6跟前面映射出来的特征一样


    inner_product = mapped_cord@ theta #.as_matrix()      #相当于执行theta1+theta2*x1+theta3*x2.......theta28*x2^6等于0或无线接近0就符合
    #上面这一句和下面这一句相比这样写有什么影响吗
    inner_product = mapped_cord.as_matrix()@ theta        #
    
    decision = mapped_cord[np.abs(inner_product) < threshhold]  #判断函数threshhold相当于一个接近0的数


    return decision.f10, decision.f01
#寻找决策边界函数

我如果按第二句写会报错但第一句不会为什么啊

1、梯度下降问题:这个不是你写的吗,你怎么问我【doge】

要有数学公式配代码


2、as_matrix方法已经被弃用了吧,现在是.values;就是把pandas类型的数据转为numpy的(你找一下新的博客以及代码研究吧)

numpy中的数组或矩阵进行运算,比如a(m*n)和b(n*k),要符合运算格式a@b矩阵运算结果result(m

*k)

a 、b如果维数不符肯定报错,你可以打印出来看一下

print(a.shape)

不是我的意思是如果把X,Y theta写成矩阵的形式就会一直报错 怎样才能用矩阵来实现

def computeCost(theta, X, y):
    X = np.matrix(X)
    y = np.matrix(y)
    ''' cost fn is -l(theta) for you to minimize'''
    first = -y*np.log(sigmoid(X * theta.T))
    second = (1 - y)*np.log(1 - sigmoid(X * theta.T))
    return np.sum(first - second) / (len(X))

def gradientdescent(theta, X, y,alpha,iters):
    X = np.matrix(X)
    y = np.matrix(y)    
    parameters = int(theta.ravel().shape[1])
    temp = np.matrix(np.zeros(theta.shape))
    error = sigmoid(X * theta.T) - y
    for i in range(iters):
        temp = theta - (alpha / len(X))*np.multiply(X.T,(X*theta.T-y))
        theta = temp    
        cost = computeCost(theta, X, y)
    return theta, cost
#就是梯度下降这里用矩阵的形式就会一直报错 如果我不写np.matrix()的话 全部X*theta.T改成X@theta程序就可以正常运行
def get_Xy(df):#读取特征
    ones = pd.DataFrame({'ones': np.ones(len(df))})#ones是m行1列的dataframe
    data = pd.concat([ones, df], axis=1# 合并数据,根据列合并 axis = 1的时候,concat就是行对齐,然后将不同列名称的两张表合并 加列
    X = data.iloc[:, :-1# 这个操作返回 ndarray,不是矩阵
    X= X.values
    y = data.iloc[:, -1]
    y = y.values
    return X,y

def gradientdescent(theta, X, y,alpha,iters):
    temp = np.zeros(theta.shape)
    error = sigmoid(X @ theta) - y            #sigmoid(X * theta.T) - y
    for i in range(iters):
        temp = theta - (alpha / len(X))*X.T@(sigmoid(X@theta) - y)  #theta - (alpha / len(X))*X.T@(sigmoid(X*theta.T) - y)
        theta = temp    
        cost = computeCost(theta, X, y)
    return theta, cost
def computeCost(theta, X, y):
    ''' cost fn is -l(theta) for you to minimize'''
    first = -y*np.log(sigmoid(X @ theta))   #np.multiply(-y,np.log(sigmoid(X * theta.T)))
    second = (1 - y)*np.log(1 - sigmoid(X @ theta))   #np.multiply((1-y),np.log(1-sigmoid(X * theta.T)))
    return np.sum(first - second) / (len(X))
X, y = get_Xy(data)
print(X.shape)   #(100,3)
print(y.shape)   #(100,)
theta = np.zeros(3)
theta.shape      #(3,)
#改成矩阵的替换代码
#X = np.matrix(X)
#y = np.matrix(y) 
#theta = np.matrix(theta)
#theta = theta.reshape(1,3)


alpha = 0.003
iters = 200000
g, s = gradientdescent(theta, X, y,alpha,iters)
print(g, '\n', s)

#这样可以正常运行但如果我把theta x y 变成矩阵的话就会报错,如图把注释里的代码放出来替换相应代码 x y theta都设置为矩阵的形式一直出错,通过了运行结果也不对