回归中的overfittingunderfitting,正则化回归python

前端之家收集整理的这篇文章主要介绍了回归中的overfittingunderfitting,正则化回归python前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Adressing overfitting:

  • 减少特征
  • 模型选择,自动选择变量
    但是特征信息的舍弃会导致信息的丢失

regularization:

  • 保留所有特征,但是减少参数theta的值
  • 在很多特征时有良好的效果

cost function

对参数惩罚,保证参数较小,防止过拟合
1. fitting well
2. theta is small

这里的lambda参数设置过大会underfitting

正则化回归

正则化回归中的只惩罚非常数项所以,将梯度下降分开:

Normal equation

正则化通过在对角加上一个数值,可是解决不可逆的问题.

逻辑回归正则化

无正则化的逻辑回归的cost function

正则化的cost

梯度下降的式子与线性的相同,不同的是h(theta)函数不同

其损失函数为:

整个迭代过程为:

  1. __author__ = 'Chen'
  2.  
  3. from numpy import *
  4.  
  5. #calculate the cost
  6. def costFunction(X,Y,theta):
  7. mse = (theta * X.T - Y.T)
  8. return mse *mse.T
  9. #linearReresion
  10. def linearRegresion(x,y,type=True,alpha=0.01,lambdas=0.01):
  11.  
  12. xrow = shape(x)[0]
  13. xcol = shape(x)[1]
  14. x = matrix(x)
  15. Y = matrix(y)
  16. # fill ones
  17. xone = ones((xrow,1))
  18. X = hstack((xone,x))
  19. X = matrix(X)
  20. # normal equiation
  21. if type == True:
  22. #add regularization
  23. for i in range(1,xrow):
  24. X[i,i] += lambdas * 1
  25. theta = (X.T*X).I*X.T*Y
  26. return theta
  27. else:
  28.  
  29. # gradiant
  30. theta = matrix(random.random(xcol+1))
  31. # iterations
  32. for iteration in range(1,10000):
  33. # return the cost
  34. print costFunction(X,theta)
  35. sums = 0
  36. #gradient method
  37. # adding a regularzation need to add theta(i-1)
  38. temptheta = theta
  39. temptheta[0,0] = 0
  40.  
  41. for i in range(1,xrow):
  42. sums += (theta*X[i,:].T-Y[i,:])*X[i,:]
  43. theta -= alpha*sums/xrow + lambdas * temptheta/xrow
  44. return theta
  45.  
  46.  
  47.  
  48. x= [[0,1,0],[0,0,1],[1,1]]
  49. y= [[1],[2],[3],[4]]
  50.  
  51. # calculate linearRegression by normal equation
  52. theta1 = linearRegresion(x,y)
  53. print theta1
  54.  
  55. #gradient descent
  56. theta2 = linearRegresion(x,False)
  57.  
  58. print theta2

猜你在找的正则表达式相关文章