千家信息网

Java线性回归基础代码怎么写

发表于:2025-11-16 作者:千家信息网编辑
千家信息网最后更新 2025年11月16日,这篇文章主要介绍"Java线性回归基础代码怎么写",在日常操作中,相信很多人在Java线性回归基础代码怎么写问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Java线性回
千家信息网最后更新 2025年11月16日Java线性回归基础代码怎么写

这篇文章主要介绍"Java线性回归基础代码怎么写",在日常操作中,相信很多人在Java线性回归基础代码怎么写问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Java线性回归基础代码怎么写"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

# Use linear model to model this data.from sklearn.linear_model import LinearRegressionimport numpy as nplr=LinearRegression()lr.fit(pga.distance[:,np.newaxis],pga['accuracy']) # Another way is using pga[['distance']]theta0=lr.intercept_theta1=lr.coef_print(theta0)print(theta1)#calculating cost-function for each theta1#计算平均累积误差def cost(x,y,theta0,theta1): J=0 for i in range(len(x)): mse=(x[i]*theta1+theta0-y[i])**2 J+=mse return J/(2*len(x))theta0=100theta1s = np.linspace(-3,2,197)costs=[]for theta1 in theta1s: costs.append(cost(pga['distance'],pga['accuracy'],theta0,theta1))plt.plot(theta1s,costs)plt.show()print(pga.distance)#调整thetadef partial_cost_theta0(x,y,theta0,theta1): #我们的模型是线性拟合函数时:y=theta1*x + theta0,而不是sigmoid函数,当非线性时我们可以用sigmoid #直接多整个x series操作,省的一个一个计算,最终求sum 再平均 h=theta1*x+theta0  diff=(h-y) partial=diff.sum()/len(diff) return partialpartial0=partial_cost_theta0(pga.distance,pga.accuracy,1,1)def partial_cost_theta1(x,y,theta0,theta1): #我们的模型是线性拟合函数:y=theta1*x + theta0,而不是sigmoid函数,当非线性时我们可以用sigmoid h=theta1*x+theta0 diff=(h-y)*x partial=diff.sum()/len(diff) return partialpartial1=partial_cost_theta1(pga.distance,pga.accuracy,0,5)print(partial0)print(partial1)def gradient_descent(x,y,alpha=0.1,theta0=0,theta1=0): #设置默认参数 #计算成本 #调整权值 #计算错误代价,判断是否收敛或者达到最大迭代次数 most_iterations=1000 convergence_thres=0.000001   c=cost(x,y,theta0,theta1) costs=[c] cost_pre=c+convergence_thres+1.0  counter=0 while( (np.abs(c-cost_pre)>convergence_thres) & (counter到此,关于"Java线性回归基础代码怎么写"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0