python中numpy运算出现overflow问题

python中numpy运算出现overflow问题

定义损失函数出现overflow

数据是吴恩达机器学习作业练习1中的,在计算损失函数和实现梯度下降,出现overflow,将数据都改成float64后,依然出现overflow

相关代码

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

#加载数据

df=pd.read_csv('ex1data1-Copy1.txt',header=None,names=['population','profit'])

df.head()

population profit
0 6.1101 17.5920
1 5.5277 9.1302
2 8.5186 13.6620
3 7.0032 11.8540
4 5.8598 6.8233

python">df_np=df.values

df_np=np.insert(df_np,0,1.0,axis=1)

df_np.shape
X=df_np[:,0:2]

X.shape

X=X.astype(np.float64)
#将y变成列向量

y=y.reshape(97,1)

y=y.astype(np.float64)

y.shape

#定义损失函数

def cost(X,y,theta):

inn=np.sum((np.dot(X,theta)-y)**2)

return inn/(2*len(y))

theta=[0.0,0.0]

theta=np.array(theta,dtype='float64').reshape(2,1)

loss_theta0=cost(X,y,theta)

loss_theta0

#更新theta

def GredientDec(X,y,theta,iters,alpha):

parameters=X.shape[1]

loss=np.zeros((iters,1))

for a in range(iters):

error=(np.dot(X,theta)-y)

for j in range(parameters):

term=np.sum(np.multiply(error,X[:,j]))

theta[j]=theta[j]-(alpha*term)/len(y)

loss[a]=cost(X,y,theta)

return theta,loss

np.seterr(invalid='ignore')

theta,loss=GredientDec(X,y,theta=theta,iters=1000,alpha=0.01)

theta

报错信息:<ipython-input-10-494f352e9efa>:6: RuntimeWarning: overflow encountered in square
inn=np.sum((np.dot(X,theta)-y)**2)
E:\Anaconda\lib\site-packages\numpy\core\fromnumeric.py:87: RuntimeWarning: overflow encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)

没有传文件的地方,只能把数据文件放在百度网盘了,麻烦了!
数据地址:
链接:https://pan.baidu.com/s/1Fp84...
提取码:r7fc
--来自百度网盘超级会员V5的分享

请问为啥出现overflow,数据都是浮点型啊,还有如何解决这一问题啊(新手入门,多多包含)

以上是 python中numpy运算出现overflow问题 的全部内容, 来源链接: utcz.com/p/938403.html

回到顶部