AI智能
改变未来

解决在使用numpy.polyfit 时出现的 raise LinAlgError(\”SVD did not converge in Linear Least Squares\”)错误

#测试talib模块import talibimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltdf = []close_list = []f = open(\"trade_records/contract_data_HOUR.txt\",\'r\')data = f.readlines()for item in data:df.append(eval(item))f.close()print(df)df = pd.DataFrame(df)print(df)real = talib.MA(df.close,timeperiod=3)print(real)x=range(0,len(real)-2,1)y= real[2:]#求x,y的多项式z1 = np.polyfit(x,list(y),6)p1 = np.poly1d(z1)# 转换成多项式表达式yvals = p1(x) #求得拟合函数yvals#绘制拟合曲线plt.plot(x,y,\'b--\',label=\'original values\')plt.plot(x,yvals,\'r\',label=\'polyfit values\')plt.xlabel(\'Time\')plt.ylabel(\'Price\')plt.legend(loc=3)plt.show()

real的值为:

0          NaN1          NaN2     3.6060003     3.5843334     3.5800005     3.5723336     3.5850007     3.5890008     3.5996679     3.59300010    3.58500011    3.57566712    3.55700013    3.54400014    3.56200015    3.59000016    3.61333317    3.59833318    3.59000019    3.577000dtype: float64

在上面的例子中,real的前两个值为np.NaN型,因此无法进行plot,进而会出现LinAlgError错误,只需要将非法值去掉后就可以正常运行了;

运行结果:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 解决在使用numpy.polyfit 时出现的 raise LinAlgError(\”SVD did not converge in Linear Least Squares\”)错误