背景

学校竟然会讲机器学习
现在是下载一个anaconda,我已经有pycharm,所以选择的方案是
jupyter notebook + anaconda(学校推荐的初学者方案,单行代码单行显示,比较方便)
pycharm + anaconda(bilibili有的教学视频是用pycharm,也没浪费)

关于anaconda的用法,是直接自己创建虚拟环境,到ide里直接配置它生成的虚拟环境就好了。
关于jupyter notebook打开方式,打开Anaconda Prompt输入jupyter notebook浏览器会弹出一个交互界面(这个界面的服务器在本地)
PS:jupyter notebook一进去显示的根目录是输入“jupyter notebook”时所在的位置
(可是我还不会调默认路径,每次一进bash shell就要重新输路径

PS:吐槽

  • 用anaconda navigator去安装包,竟然没有pygal,我还要跑到中端去pip
  • jupyter notebook的分行代码输出,只会输出这个块的最后一行元素

python基础课程

定义

  • 关于python是解释型语言
    编译型语言(如 C、C++)在执行程序之前,需要通过编译器将源代码一次性翻译成目标机器的机器码,生成可执行文件,之后直接运行这个可执行文件。而解释型语言则是在程序运行时,由解释器逐行读取源代码,并将其翻译成机器可执行的指令,然后立即执行
  • Python 作为交互式语言的特点
    实时反馈:在 Python 的交互式环境中,你可以逐行输入代码并立即看到执行结果

操作

注释方式

单行注释用#
多行用"""'''

数据结构

  • 数字:int, long, float, complex
  • 字符串:', ",'''
  • 元组:比如a_tuple = (1, 0.2, '0.3', 'data')。不能二次赋值,相当于只读列表,内部带有索引,从0开始编号。count()对象出现的次数。index()对象出现的位置
  • 列表:[]
  • 集合:遵循集合论的运算方法,返回无序,无重复的集合
  • 字典:无序。key - value

列表的特殊结构

通过可推导的公式编写列表

1
2
3
4
5
6
7
8
9
10
a_list = [i for i in range(9)] 
#range(9):这会生成一个从 0 到 8 的整数序列,即 0, 1, 2, 3, 4, 5, 6, 7, 8。
#for i in range(9):此为迭代部分,它会依次从 range(9) 里取出每个元素,并将其赋值给变量 i。
#i:这是表达式部分,意味着直接把从 range(9) 中取出的元素 i 作为新列表的元素。

a_list = [i ** 2 for i in range(9)]
#i ** 2:这是表达式部分,表示把这个数字放进列表

a_list = [[i + j for i in range(5)] for j in range(9)]
#这是一个嵌套的列表推导式,外层列表推导式控制二维列表的行数,内层列表推导式控制每行的元素个数

列表的插入与删除

1
2
a_list.insert(0, 'stuff')#插入
a_list.pop(0)#删除。指的是删除第几个位置上的元素

列表的排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
b_list = sorted(a_list)
#对于sorted()
#用于对可迭代对象(如列表、元组、字符串等)进行排序操作。它会返回一个新的已排序的列表,而不会改变原可迭代对象的内容
'''
sorted(iterable, key=None, reverse=False),其中:
iterable:必需参数,表示要进行排序的可迭代对象,这里就是 a_list。
key:可选参数,是一个函数,用于指定在排序时对每个元素进行处理的规则。默认值为 None,表示直接比较元素本身。
reverse:可选参数,是一个布尔值,用于指定排序的顺序。reverse=False 表示升序排序(默认值),reverse=True 表示降序排序。

lambda 函数是 Python 中的匿名函数,它可以在需要函数对象的地方临时定义一个简单的函数。其基本语法为 lambda arguments: expression,其中:
arguments:表示函数的参数。
expression:表示函数的返回值。
在 sorted(a_list, key = lambda x:x[1]) 中,lambda x:x[1] 表示定义了一个匿名函数,该函数接受一个参数 x,并返回 x 的第二个元素(索引为 1)。
'''

基本语句

条件语句if-elif-else
循环for,while

模块

包——多个py文件——一个目录,包含——init.py文件
模块——一个py文件
类class
函数function
代码块block

包管理工具——pip
pip --version, pip list, pip install/uninstall

模块调用。import与from(从客户端)

函数

函数定义: def xxx():

用来区分当前脚本是作为主程序直接运行,还是作为模块被其他脚本导入使用——if __name__ == '__main__'
当脚本作为主程序直接运行时,name 的值会被自动设置为 ‘main‘。
当脚本作为模块被其他脚本导入时,name 的值会被设置为该脚本文件的名称(不包含 .py 扩展名)。

匿名函数lambda,lambda表达式所返回的函数对象与由def创建并赋值的函数对象工作区来基本一致
lambda x: x**2接受x,返回x**2

文件操作

打开函数(需要文件路径与打开方式)——file = open(file_path, 'r')
关闭函数——file.close()

路径函数——os.path.realpath('xxxx.ipynb'), os.path.dirname(current_file), os.path.join(os.path.dirname(current_dir), 'data')
关于对os.path 模块的使用
os.path.realpath(path) 函数用于返回指定路径的真实路径。如果路径中包含符号链接,该函数会将其解析为实际的物理路径。
os.path.dirname(path) 函数用于返回指定路径的目录部分。也就是说,它会去掉路径中的文件名,只返回文件所在的目录路径。
os.path.dirname(current_dir) 用于获取 current_dir 路径的目录部分。
os.path.join(path1, path2, …) 函数用于将多个路径组件连接成一个完整的路径,它会根据操作系统的不同自动处理路径分隔符。

文件读取——with open(file_path, 'r') as simple_file, simple_file = open(file_path, 'r')
隐式读取与显式读取

写入——my_file.write('xxxx')
删除(需要先通过if os.path.exists(new_path)确认文件是否存在)——os.remove(new_path)

OOP(面向对象编程)

class声明类后要用__init__(函数填入属性,实例化)
当你创建一个类的对象时,Python 会自动调用 init() 方法,你可以在这个方法里对对象的属性进行初始化设置,确保对象在创建后就具备合适的初始状态。

init() 方法可以接收参数,这些参数通常用于设置对象的属性值。

第一个参数必须是 self,它代表类的实例本身,通过 self 可以访问和修改对象的属性。

1
2
3
4
5
6
7
8
9
10
11
12
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def introduce(self):
print(f"我叫 {self.name},今年 {self.age} 岁。")

# 创建 Person 类的实例
p1 = Person("张三", 25)
# 调用实例的方法
p1.introduce()

alt text
alt text
alt text
alt text
alt text

python库函数

python科学栈(Scientific Stack)是python库的集合的统称,包括:

  • Numpy,n维数组
  • Scipy,用于科学计算的技术库
  • Matplotlib,二维图形的输出
  • Ipython,交互式的
  • Sympy,符号数学
  • Pandas,数据结构及分析

Numpy

易错:注意,x = np.array([1, 2, 3])
这是中括号在小括号里面

1
2
3
4
5
6
7
8
import numpy as np

#使用array()函数创建数组
c = np.array([[1,2,3], [4,5,6]])
d = np.array(((1,2,3),(4,5,6)))
g = np.array([(1,2,3),[4,5,6]])
e = np.array([['a','b'],['c','d']])
f = np.array([[1,2,3],[4,5,6]], dtype=complex)

对于数组进行算术运算,是对每个元素分别,同时进行
python中没有++或–,用+=

1
2
3
4
5
6
7
8
#运算

a * np.sin(b)
a * np.sqrt(b)#np.sqrt(b) 指b的平方根
A = np.arrage(0,9).reshape(3,3)
B = np.ones((3,3))
A * B #这是对应位置上的元素相乘
np.dot(A,B)#这是矩阵乘法

数组变形:
reshape():转换数组的形状,是其中数据重新排列
ravel():将多维数组转换为一维数组
transpose():行列转置


alt text

Matplotlib

  • 散点图(scatter plot)
    1
    2
    3
    4
    5
    6
    7
    8
    import matplotlib as plt

    plt.axis([0,5,0,20])
    plt.title('My first plot')
    plt.plot([1,2,3,4],[1,4,9,16], 'ro')#两个列表分别表示x,y轴坐标ro代表输出点的颜色为红色
    plt.show()

    ###被封装起来的x,y变量,再来制作散点图,plt.scatter(x, y, color='blue')
    如果把两个数据作对比输出到同一个图中
    就要注意数据的封装,横坐标要一致
  • 线图(line plot)
  • 柱状图(bar plot)
  • 3d图(3d plot)
使用matplotlib

要导入的是import matplotlib.pyplot as plt
用的是matplotlib的子模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

plt.plot(t, s, 'r')
font = FontProperties(fname = r"c:\windows\fonts\simsun.ttc", size = 14)
plt.title(u'Voltage/Time', fontproperties = font)
plt.xlabel(u'Time(s)', fontproperties = font)
plt.ylabel(u'Voltage(mV)', fontproperties = font)

plt.savefig("test.png")


当有多条曲线时
用参数来区分颜色(颜色取英文单词也可以)

符号 代码 符号 代码 符号 代码 符号 代码
g 绿色 b 蓝色 c 蓝绿色 m 品红色
. v 实心倒三角 ^ 实心三角 o 实心圆
* 实心五角星 + 加号 s 实心方块 - 实线
虚线 -. 点划线

用法:plt.plot(t, y1, 'b*', t, y2, 'g^', t, y3, 'ys')
跑龙套。plot(t, y1, 'b--', t, y2, 'g', t, y3, 'r--')

Sudplot绘制子图

1
2
3
4
5
6
7
8
9
plt.subplot(2, 1, 1)#第一个子图设置,2 行 1 列的子图布局,编号1
plt.plot(x, y_sin)
plt.title('Sine')

plt.subplot(2, 1, 2)#第二个子图设置
plt.plot(x, y_cos)
plt.title('Cosine')

plt.show()
pygal实现数据可视化

显示掷色子的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from random import randint
import pygal

results = []
for i in range(1000):
result = randint(1, 6)
results.append(result)

frequencies = []
for value in range(1, 7):#range(1, 7) 会生成一个从 1 到 6 的整数序列
frequency = results.count(value)
frequencies.append(frequency)

#########下面是图表可视化##########
hist = pygal.Bar()
hist.title = 'Frequency of each number'
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = 'result'
hist.y_title = 'Frequency of each number'
hist.add('D6', frequencies)
hist.render_to_file('result.svg')

alt text

Pandas

基础是Numpy,Scipy,Matplotlib

数据结构:

  • 一维数据结构——Series——pd.Series(data, index[])
    可以通过索引的方式获取Series中的单个或一组值,若index为空,则为默认索引,0,1,2…
    s= pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
    alt text
  • 二维数据结构——DataFrame——pd.DataFram(data, columns = [], index = [])columns为列索引,index为行

alt text
alt text

  • 三维数据结构——Panel
    alt text
    I/O操作:
  • 读写CSV文件
    alt text
  • 读写Excel文件
    alt text
Seaborn

是基于matplotlib的统计数据的图形可视化工具
具有更高层级的封装,使用更简洁
相较于matplotlib要手动调整参数,seaborn有默认的参数,主题供选择

分为两类。区别在于是否有图框

  • figure-level,图级别能绘制多种图像
    图级函数会创建一个新的图形窗口,并根据需要创建子图布局,方便一次性绘制多个相关的图形。
  • axes-level,轴级别——只能绘制一种图像
    轴级函数只会在指定的 Axes 对象上绘制图形,不会创建新的图形窗口或子图布局。
    alt text
    alt text
displot vs histplot 直方图

区别在于一个是图级函数,一个是轴级函数
alt text
alt text

displot vs kdeplot 概率密度图

alt text

displot vs ecdf 经验累积函数

alt text

displot vs 多变量

alt text

relplot vs scatterplot 散点图


alt text
alt text

relplot vs lineplot 折线图

alt text

jointplot vs pairplot 散点图与密度图的组合

alt text

catplot-scatter

alt text

catplot-distribute 箱子图

alt text
alt text

catplot-statistic

alt text
alt text

回归分析

alt text
alt text
alt text

练习

数据结构

题目:记录通讯录
回答:

1
2
3
def contacts(name, phone):
contact = {"name":name, "phone"phone}
contacts.append(contact)

关于对象进行编程

题目:有一只猫,有颜色color,动作jump,用类来描述
实例化一只猫,跳了两步
答案:

1
2
3
4
5
6
7
8
9
class Cat:
def __init__(self, color):
self.color = color
def jump(self, step):
self.step = step
print(f"这只{self.color}猫跳了{step}步")
#这是在函数里面,这个里面有的变量step不用再拿self来引
blackcat = Cat("黑色")
blackcat.jump(2)

matplotlib绘图

题目:绘制一组散点图,颜色为蓝色
纵坐标为40,20,50,70,10
横坐标为10,20,40,60,100
答案:

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
import matplotlib.pyplot as plt

x = np.array([10, 20, 40, 60, 100])
y = np.array([40, 20, 50, 70, 100])

plt.scatter(x, y, color = 'blue')
plt.title('plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

plt.show()

Seaborn库的使用

问题:绘制iris数据集的联合分布和边缘分布。联合分布使用回归分析
(。。。看不懂这些名词)
答案:

1
2
3
4
5
6
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")#调用自带的数据
plt.rcParams['figure.dpi'] = 300
g = sns.jointplot(data = iris, x = "sepal_length", y = "sepal_width", kind = "reg")
plt.show()

易错,不要把python和c搞混

  • python声明变量时不需要类型定义
  • 声明字典用def,声明对象用class
  • python的注释不是//,而是#
  • range(1, 7) 会生成一个从 1 到 6 的整数序列
  • 等于是==,不等是!=,不要写成!==。。。。。。。。。