Python函数不断返回nan?
我目前正在通过重写我用其他语言编写的一些旧程序来学习python。但由于某种原因,我一直遇到一个问题,函数调用总是返回一个nan。下面是一段代码片段 如果我在梯度下降函数外调用函数theta0PartialDerivative,它将返回一个数字,否则返回一个nan。我不确定问题是什么Python函数不断返回nan?,python,nan,Python,Nan,我目前正在通过重写我用其他语言编写的一些旧程序来学习python。但由于某种原因,我一直遇到一个问题,函数调用总是返回一个nan。下面是一段代码片段 如果我在梯度下降函数外调用函数theta0PartialDerivative,它将返回一个数字,否则返回一个nan。我不确定问题是什么 def theta0PartialDerivative(): multBy=40.0 total=temp=0 for i in range(40): temp+=thet
def theta0PartialDerivative():
multBy=40.0
total=temp=0
for i in range(40):
temp+=theta0
temp+=theta1*sepalWidth[i]
temp+=theta2*petalLength[i]
temp+=theta3*petalWidth[i]
temp-=sepalLength[i]
total=total+temp
temp=0
return (multBy*total)
def gradientDescent():
alpha=0.5
global theta0,theta1,theta2,theta3
theta0After=theta1After=theta2After=theta3After=1
while(theta0After!=theta0 and theta1After!=theta1 and
theta2After!=theta2 and theta3After!=theta3):
theta0=theta0After
theta1=theta1After
theta2=theta2After
theta3=theta3After
theta0After=theta0 - (alpha * theta0PartialDerivative())
theta1After=theta1 - (alpha * theta1PartialDerivative())
theta2After=theta2 - (alpha * theta2PartialDerivative())
theta3After=theta3 - (alpha * theta3PartialDerivative())
theta0=theta1=theta2=theta3=accuracy=0
gradientDescent()
完整文件在此:
编辑:真的吗?没有人知道问题是什么?发现了问题。阶跃变量Alpha对于我正在处理的数据集来说太大,导致偏导数发散而不是收敛。我将alpha值从0.5改为0.13,它可以正常工作您可以演示如何在gradientDescent函数中调用它吗?你能为两个函数调用附上图解结果吗?分享更多的代码,因为这里的内容似乎不够丰富,我确实展示了如何将其称为theta0After=theta0-alpha*theta0部分派生。如果我在它打印nan的函数内部写入printtheta0PartialDerivative,则在它的外部打印-8059.9999999999。您还需要什么代码?萼片/花瓣长度/宽度都是整数列表。我正在读取一个包含50条记录的txt文件,并使用其中的40条来训练一个函数,以使用其他3个属性预测萼片长度。@Davidsidarus这里是一个python文件的repo:
def theta0PartialDerivative():
multBy=40.0
total=temp=0
for i in range(40):
temp+=theta0
temp+=theta1*sepalWidth[i]
temp+=theta2*petalLength[i]
temp+=theta3*petalWidth[i]
temp-=sepalLength[i]
total=total+temp
temp=0
return (multBy*total)
def gradientDescent():
alpha=0.5
global theta0,theta1,theta2,theta3
theta0After=theta1After=theta2After=theta3After=1
while(theta0After!=theta0 and theta1After!=theta1 and
theta2After!=theta2 and theta3After!=theta3):
theta0=theta0After
theta1=theta1After
theta2=theta2After
theta3=theta3After
theta0After=theta0 - (alpha * theta0PartialDerivative())
theta1After=theta1 - (alpha * theta1PartialDerivative())
theta2After=theta2 - (alpha * theta2PartialDerivative())
theta3After=theta3 - (alpha * theta3PartialDerivative())
theta0=theta1=theta2=theta3=accuracy=0
gradientDescent()