如何解决python2 .x到python 3.x:'float'和'NoneType'实例之间不支持'>'
在python 3.x版本中执行(Python 2.x代码)时发生以下错误:
" File "C:\Users\silen\Documents\♠ Asset Allocation
Project\HRP(Hierarchical Risk Parity)_py2.7\Python3.7\CLA.py",line
47,in solve
if (self.l[-1] is None or l<self.l[-1]) and l>l_out:l_out,i_out=l,i
TypeError: '>' not supported between instances of 'float' and 'NoneType' "
解决方案是什么?
class CLA:
def __init__(self,mean,covar,lB,uB):
# Initialize the class
self.mean=mean
self.covar=covar
self.lB=lB
self.uB=uB
self.w=[] # solution
self.l=[] # lambdas
self.g=[] # gammas
self.f=[] # free weights
def solve(self):
# Compute the turning points,free sets and weights
f,w=self.initAlgo()
self.w.append(np.copy(w)) # store solution
self.l.append(None)
self.g.append(None)
self.f.append(f[:])
while True:
#1) case a): Bound one free weight
l_in=None
if len(f)>1:
covarF,covarFB,meanF,wB=self.getMatrices(f)
covarF_inv=np.linalg.inv(covarF)
j=0
for i in f:
l,bi=self.computeLambda(covarF_inv,wB,j,[self.lB[i],self.uB[i]])
if l>l_in:l_in,i_in,bi_in=l,i,bi
j+=1
#2) case b): Free one bounded weight
l_out=None
if len(f)<self.mean.shape[0]:
b=self.getB(f)
for i in b:
covarF,wB=self.getMatrices(f+[i])
covarF_inv=np.linalg.inv(covarF)
l,meanF.shape[0]-1,\
self.w[-1][i])
if (self.l[-1] is None or l<self.l[-1]) and l>l_out:l_out,i
if (l_in is None or l_in < 0) and (l_out is None or l_out < 0):
#3) compute minimum variance solution
self.l.append(0)
covarF,wB=self.getMatrices(f)
covarF_inv=np.linalg.inv(covarF)
meanF=np.zeros(meanF.shape)
else:
#4) decide lambda
if l_in>l_out:
self.l.append(l_in)
f.remove(i_in)
w[i_in]=bi_in # set value at the correct boundary
else:
self.l.append(l_out)
f.append(i_out)
covarF,wB=self.getMatrices(f)
covarF_inv=np.linalg.inv(covarF)
#5) compute solution vector
wF,g=self.computeW(covarF_inv,wB)
for i in range(len(f)):w[f[i]]=wF[i]
self.w.append(np.copy(w)) # store solution
self.g.append(g)
self.f.append(f[:])
if self.l[-1]==0:break
#6) Purge turning points
self.purgeNumErr(10e-10)
self.purgeExcess()
def getCLA(cov,**kargs):
# Compute CLA's minimum variance portfolio
mean = np.arange(cov.shape[0]).reshape(-1,1)
# Not used by C portf
lB = np.zeros(mean.shape)
uB = np.ones(mean.shape)
cla = CLA.CLA(mean,cov,uB)
cla.solve()
return cla.w[-1].flatten()
w_ = pd.Series(getCLA(cov=cov_,corr=corr_))
解决方法
您无法在Python 3中比较不同的类型。幸运的是,在这种情况下,看起来所有新的l
都是float
,而您只想将“小于所有”的值作为初始化程序,对于float
with -inf
来说很简单:
from math import inf
...
l_in = -inf # Instead of None
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。