爬向数据分析 2020-07-31 00:40 采纳率: 0%
浏览 34
已结题

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(),请问是为什么,有什么解决办法吗,我目前只能够在函数里面单独处理要调用的参数当做局部变量保持维度一致,一旦在函数外面当做全局变量设置维度一致的话就会出问题
  • 写回答

20条回答 默认 最新

  • PythonJavaC++go 2020-07-31 09:06
    关注
    theta = np.zeros([3,1]) # 你这个是不是有问题?
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题