微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Scipys fmin bfgs 导致类型错误和值错误

如何解决Scipys fmin bfgs 导致类型错误和值错误

在实现逻辑回归时遇到问题。 此代码

from sigmoid import sigmoid
import numpy as np
import pandas as pd
from j_cost_reg import j_cost_reg
import csv
from scipy.optimize import fmin_bfgs


data_1415=pd.read_csv(myFile)
y_all=data_1415['R']
X=data_1415.drop(['R'],1)

## MEAN norMALIZATION
X.insert(0,'0',1)
mean=X.mean()
std=X.std()
X=(X-mean.transpose())/std.transpose()
#Initialize theta parameters
initial_theta = np.zeros(shape=(X.shape[1],1))

#regularization term
l = 1

cost,grad = j_cost_reg(initial_theta,X,y_all,l)

def decorated_cost(theta):
    return j_cost_reg(theta,l)

print(fmin_bfgs(decorated_cost,x0=initial_theta))

有了这个代价函数

import numpy as np
##Vectorized implementation with regularization

def j_cost_reg(theta,y,l):
        X=np.array(X)
        y=np.array(y)
        theta=np.array(theta)
        theta=np.reshape(theta,(len(theta),1))
        m=len(y)
        y=np.reshape(y,(m,1))
        J=0
        thetareg=theta.copy()
        thetareg[0]=0 #first term shouldn't be regularized
        h=sigmoid(X.dot(theta))
        J=(-1/m)*np.sum((y*np.log(h)+(1-y)*np.log(1-h)))+(l/(2*m))*np.sum(thetareg**2);
        B=h-y
        grad=(X.T).dot(B)+thetareg*(l/m)  
     
        return J,grad.T.flatten()

导致此错误

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
  return array(a,dtype,copy=False,order=order,subok=True)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

    J_transposed[i] = df / dx
ValueError: setting an array element with a sequence.

谁能找出问题所在?

我尝试了成本函数的不同实现以及我的数据的结构方式,但似乎没有任何效果。我也尝试过使用其他人编写的成本函数,但得到同样的错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。