python 用matplotlib 画图

随机梯度上升的图:

需要注意的是给数据加分类标签时候,画散点图时候直接返回type,而画plot时候返回的是元组 即type3,

此外,数据要以np.array形式给出才能画直线

def plotBestFit(weights,dataMat,labelMat):
    dataArr = np.array(dataMat) #注意这里
    n = np.shape(dataArr)[0]
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i]) == 1:
            xcord1.append(dataArr[i,1])
            ycord1.append(dataArr[i,2])
        else:
            xcord2.append(dataArr[i,1])
            ycord2.append(dataArr[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    type1 = ax.scatter(xcord1,ycord1,s=30,c='red',marker='s')
    type2 = ax.scatter(xcord2,ycord2,s=30,c='green')
    x = np.arange(-3.0,3.0,0.1)
    y = (-weights[0]-weights[1]*x)/weights[2] #weights需要是np.array类型
    # print(y)
    type3, = ax.plot(x,y)
    plt.legend([type1, type2, type3], ("Did Not Like", "Liked in Small Doses", "Liked in Large Doses"),loc=2)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.savefig('regression.pdf')#保存图片为pdf格式
    plt.show()


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值