liuyubobobo《机器学习》学习笔记(六)

numpy和matplotlib (3)


1.matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt    # 常用

最基础的用法

import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()         # Jupyter Notebook上不用show()也可以显示出来

在这里插入图片描述

支持两条曲线,并设置参数

x = np.linspace(0, 10, 100)
cosy = np.cos(x)
siny = np.sin(x)
plt.plot(x, siny)
plt.plot(x, cosy, color="red", linestyle=':')   # color:颜色  linestyle:虚线,……
plt.show()

在这里插入图片描述

设置x,y轴的区间和名称

plt.plot(x, siny)
plt.plot(x, cosy, color="red", linestyle='--')
plt.xlim(-5, 15)
plt.ylim(0, 1.5)
# 另一种方法
# plt.axis([-5, 15, 0, 1.5])
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()

在这里插入图片描述

给曲线添加label

plt.plot(x, siny, label = "sin(x)")
plt.plot(x, cosy, color="red", linestyle='--', label = "cos(x)")
plt.xlim(-5, 15)
plt.ylim(0, 1.5)
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.legend()  # 别忘了这句!!
plt.show()

在这里插入图片描述

给图添加标题

plt.plot(x, siny, label = "sin(x)")
plt.plot(x, cosy, color="red", linestyle='--', label = "cos(x)")
plt.axis([-1, 11, -2, 2])
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.legend()
plt.title("Welcome to the ML World!")
plt.show()

在这里插入图片描述

2.Scatter Plot 散点图 (用于二维特征)
plt.scatter(x, siny)
plt.show()

在这里插入图片描述

x = np.random.normal(0, 1, 10000)
y = np.random.normal(0, 1, 10000)
plt.scatter(x, y, alpha=0.1)  # alpha:透明度
plt.show()

在这里插入图片描述

3.应用实例(鸢尾花数据集)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets      # 导入数据集
iris = datasets.load_iris()       # 鸢尾花数据
# iris其实是一个dictionary, 可以查看其所有键
iris.keys()
# dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])
iris.DESCR   # 查看描述

在这里插入图片描述

# iris.data 是所有数据,形状(150, 4)
# iris.target 是所有标签,形状(150,)
iris.data.shape
# (150, 4)
iris.target.shape
# (150,)
iris.target_names
# array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
# 可见共有三个种类的鸢尾花,它们的值分别为0,1,2

作图

X = iris.data[:, :2]   # 只取前两个特征
plt.scatter(X[:, 0], X[:, 1])   # 画散点图
plt.show()

在这里插入图片描述

为了将不同种类的点表示出来,可以设置一些参数

y = iris.target
plt.scatter(X[y == 0, 0], X[y == 0, 1], color="red", marker="o")
plt.scatter(X[y == 1, 0], X[y == 1, 1], color="blue", marker="+")
plt.scatter(X[y == 2, 0], X[y == 2, 1], color="green", marker="x")
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值