使用matplotlib画拟合曲线的基本方法

        import matplotlib.pyplot as plt
        fig = plt.figure()
        ax = fig.add_subplot(111)
        
        ax.scatter(xSortRawArr, ySortRawArr)  
        ax.plot(xSortRawArr, ySortHatArr)

        plt.show()

 

scatter:画原始点

plot:画拟合曲线

 

这样就实现了回归图的拟合效果图。

 

当然由于有很多拟合情况,具体效果还是需要调参,然后看效果,以及十折交叉验证,选择一个泛化最好的算法

 

pyplot.plot()

在使用岭回归时,发现使用二维数组作为参数,也可以画出曲线,例如:yArr = array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [15,16,17,18]])

直接使用yArr的话,将以列数据作为y轴的数据,而x轴,则按照常样本的个数,进行自然数增长。代码为:

       import matplotlib.pyplot as plt
        fig = plt.figure()
        ax = fig.add_subplot(111)

        yArr = array([[1,2,3,4], [5,6,7,8], [9, 10, 11, 12], [15, 16, 17, 18]])
       
        ax.plot(yArr) 
        plt.show()

结果:

 

当然,可以使用自定义的x轴数据,如:xArr = arange(10,14,1),这样的话,就是自定义x轴了。代码如下:

 

        import matplotlib.pyplot as plt
        fig = plt.figure()
        ax = fig.add_subplot(111)

        yArr = array([[1,2,3,4], [5,6,7,8], [9, 10, 11, 12], [15, 16, 17, 18]])
        x = arange(10, 14, 1)
        ax.plot(x, yArr) # 此时,x轴为4个数据,因为有4个样本;yArr有4个样本,4个特征,特征值为y轴值
        plt.show()

 

结果如下:

 

利用plot画二维数据,有很大的优点:

1.可以比较不同特征值的变化过程;从这里可以引申出在不同迭代下权重参数的变化过程。比如在岭回归:

        cm_regression = CmRegression()
        abX, abY = cm_regression.loadDataSet2('abalone.txt')
        ridgeWeights = cm_regression.ridgeTest(abX, abY)
        
        xArr = arange(-10, 20, 1)

        import matplotlib.pyplot as plt
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(xArr, ridgeWeights) # 此时,x轴为xArr有30个数据;ridgeWeights 最为y轴值
plt.xlabel('log(lambda)')
plt.show()

运行结果:

 

 

posted @ 2020-08-24 19:14  绍荣  阅读(7286)  评论(0编辑  收藏  举报