导图社区 python的第三方库知识笔记
包含库安装命令,安装加速方法,基础知识库常见命令,数据分析numpy,pandas,数据展示matplotlib库常见命令。历时3年不断完善而成,可直接参考!
编辑于2024-03-21 18:13:24第三方库
库安装
pip
安装
命令行搜cmd
更新 卸载 下载但不安装 列出信息 搜第三方库 已安装的库
更新:U代表updata
卸载
下载但不安装
提升速度
换源后缀
-i https://pypi.tuna.tsinghua.edu.cn/simple
各类源
清华镜像源(大幅提升包下载速度) pip install”命令后加入“-i 源地址” pip install -U tensorflow-gpu -i https://pypi.tuna.tsinghua.edu.cn/simple(-U表示有的话直接升级) pip install jieba -i https://pypi.tuna.tsinghua.edu.cn/simple /*国内镜像源*/ 清华大学镜像源: pip install [包名] -i https://pypi.tuna.tsinghua.edu.cn/simple some-package 阿里云镜像源:pip install -i https://mirrors.aliyun.com/pypi/simple/[包名] 豆瓣镜像源:pip install [包名] -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com 中国科技大学镜像源: https://pypi.mirrors.ustc.edu.cn/simple/ 华中理工大学镜像源:http://pypi.hustunique.com/ 山东理工大学镜像源:http://pypi.sdutlinux.org/
pip install -y jupyter d2l torch torchvision -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
更新PIP
python -m pip install --upgrade pip
若能下载因为需要编译不能安装的情况
uci
Anaconda
通用描述信息获取
变量+?
a?
执行程序
%run 程序名
魔术命令
常用conda命令
conda -h/–help 查看帮助信息 conda list 列出当前环境下所有安装的 conda包。 conda search 查询 conda 包,只有经过 conda 重新编译入库的才能查 询得到 conda install scrapy=1.5.0 安装 conda update scrapy 更新 conda remove scrapy 卸载
换源提速
解决方案:更换anaconda源,使用清华的源 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ conda config --set show_channel_urls yes 再次执行升级操作,速度飞起!
最新版本安装
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/找最新版本
过坑法
#安装annaconda https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/找最新版本 #安装tensorflow库 https://blog.csdn.net/weixin_44170512/article/details/103990592 #下Github上面项目 可以把链接复制到码云下载 #清华镜像源(大幅提升包下载速度) pip install”命令后加入“-i 源地址” pip install -U tensorflow-gpu -i https://pypi.tuna.tsinghua.edu.cn/simple pip install [包名] -i https://pypi.tuna.tsinghua.edu.cn/simple /*国内镜像源*/ 清华大学镜像源:pip install [包名] -i https://pypi.tuna.tsinghua.edu.cn/simple some-package 阿里云镜像源:pip install -i https://mirrors.aliyun.com/pypi/simple/[包名] 豆瓣镜像源:pip install [包名] -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com 中国科技大学镜像源: https://pypi.mirrors.ustc.edu.cn/simple/ 华中理工大学镜像源:http://pypi.hustunique.com/ 山东理工大学镜像源:http://pypi.sdutlinux.org/
基础知识库
turtle库
窗体
子主题 1
参数解析:(窗体长,窗体宽,窗体左上角横坐标,窗体左上角纵坐标) 坐标是红圈相对篮圈的坐标,即绘图窗体相对屏幕左上角的坐标
若无后两参数,默认为屏幕中央
坐标系
子主题 1
操作
画笔控制
大小颜色
pensize(25)画笔宽度 width(25)与上边等价 pencolor(color)
RGB色彩体系
色彩参数表
设置色彩模式
起落笔
penup()起笔 pendown()落笔
运动控制
到某一点 goto(x,y)
子主题 1
一点到另一点会留下痕迹
前fd(X) X=距离(可为负数) 后bk(X)X=距离(可为负数)
fd 前进 bk 后退 circle 以左侧某点为圆心,r=半径
子主题 1
走曲线circle(r,extent=None)
1.圆心在海龟左侧即为上方 2.距离为负即圆心在下方
左右拐弯 左拐left(X)X=角度 右拐right(X)X=角度
子主题 1
子主题 1
改变方向 seth(X)X=角度
子主题 1
是否画完就关
pendone()程序运行之后不会退出,需要手工关闭窗体,若不写则会自动退出
写字
画汉字 write("要写的字",font=("字体类型",数字字号,"标准否"))
七段数码管实例 write("年",font=("Arial",18,"normal"))
隐藏海龟
hideturtle()
time库
功能
时间获取 机器内时间time() 人能懂时间ctime() 机器处理时间gmtime()
格式化
机读时间变人读 strftime(tpl,ts) 输入: tpl:格式化样式 ts:机器能处理的文本,通过gmtime()获取 输出: 特定格式时间字符串
赋值给t机器能处理的时间 格式化时间
子主题 1
人读时间变机读 strptime(str,tpl) 输入: str:要还原的时间字符串 tpl:格式化样式
程序计时 perf_counter() 输出:精确时间值
休眠 sleep(s) 输入:休眠时间s 输出:程序执行时间进程s秒
random库
功能
子主题 1
基本随机函数 种子设定seed(X)X种子 随机小数生成random()输出:0-1之间随机小数
子主题 1
子主题 2
子主题 1
拓展随机函数
某个范围内的整数或小数
给定元素选取范围随机选取元素 随机排列元素
pyinstaller库
用处
一些电脑没有安装python,不能执行代码,需要将源程序打包编译成直接可执行的程序
不需要再安装解释器即可运行
使用说明
前两个文件夹可删除 dist 与源文件同名的文件
参数,建议使用-F
加图标示例
步骤
1.写好代码 2.准备图片 3.转化图片格式 http://www.bitbug.net/ 4.代码和图片都放在administrator文件夹里 5.cmd 输入pyinstall -i 图标名.ico -F 程序名.py 6.到administrator文件夹里打开dist文件夹 7.找到exe文件创建快捷方式开用
pandas库
数据分析与高性能数据类型库
OS库
介绍
路径操作 处理文件路径和信息
引用
函数
进程管理 启动系统中其他程序
格式
环境参数 获得系统软硬件信息等环境参数
Numpy
介绍
科学计算库 *强大N维数组对象ndarray *广播功能函数 *整合C/C++代码的工具 *线性代数,傅里叶变换,随机数生成等功能 总结:是Scipy,Pandas等数据处理或科学计算库的基础
基本数据类型ndarray
优秀之处
计算简便
构成
数据 + 描述(维度和类型)
轴(axis):保存数据的维度,数据存于此 秩(rank):描述轴有多少
操作函数
元素类型
创建
列表,元组创建
列表和元组元素个数需相同
函数创建
生成0-9依次排列的数组
2*3形状的由1构成的数组
由3构成的3*3数组
5*5的单位矩阵,对角线为1,其余为0
范围创建,后边还有一个参数是颗粒度,类似于步长
类似创建函数
特殊:π的生成
0.01为颗粒度
合并数组
水平叠加
纵向叠加
m = np.vstack((a,b))

范围步长创建
Z代表把该范围平均分为几段
初值为1,末值为10,4为步长
多个范围步长创建 拉直 数组配对
x,y = np.mgrid[起始值:结束值:步长,起始值:结束值:步长.........] x.ravel() 将x变为以为数组 (拉直) np.c_[数组1,数组2 ] 使返回的间隔数值点配对
维度变换
原数组不变,总数据个数不变,因为总个数为24
降维
reshape高级用法
特定维度作行
需求:
代码:
shape (a,b,c,d) ---> shape (b∗c∗d, a)
X_flatten = X.reshape(X.shape[0], -1).T #T=转置
返回行列向量
返回行向量
返回列向量
去掉shape为1的维度
r = np.squeeze(q)
类型变换
会创建新数组
索引切片
具体值索引
a[x,y,z]xyz对应一二三维度的序号元素
切片
1: 一维度,1号元素之后都要 1:2 二维度,1号元素 1:3 三维度,1,2号元素
运算
原理
广播运算:每个元素都进行该计算
常用函数
ceil 表示超过X的最小整数值 (取整函数) floor 小于X的最大整数值
sign 正数得1 负数得-1 np.modf(a) 取数组a中各元素整数部分和小数部分
数组与数组的运算
转置运算dot
索引一图看完
数据存取
一二维数据:CSV文件
写入
分割字符为逗号 格式取整数 存入叫新文件且格式为csv格式的文件中
读取
若没有指定后边逗号分隔则会出现如下错误
多维数据
一般存取
写入
读取
便捷存取
缺点:只能有npy一种文件格式
什么时候用?
对格式无要求:用便捷存取,如缓存一段数据 对格式有要求:用CSV或者tofile方法,如交互使用
随机数函数
创建随机数组
形成2*4形状的标准正态分布且取值范围在[0,1)之间的数组
形成2*3形状,取值范围为[10,20)之间的整数数组,默认均匀分布
第一列重新排列 抽取元素
shuffle(a)不能接,接了为空 用处:随机重新排列第一列
出现重复
值越大,被选取的概率越大
生成特定分布数组
生成均值为2,标准差为1,形状为2*3的数组
返回[0,1)随机数
np.random.RandomState.rand(维度)#维度为空则返回标量
统计函数
求和 均值 加权平均 方差标准差
0轴为第一维度 38 =14+15+9
加权平均 8.4 = (14*1+2*2+14*3+6*4)/(1+2+3+4)
最大、小值及对应一维/多维索引值 极值(最大值-最小值) 中位数
一维索引值f(6)=30
求f中最小值的多维坐标
梯度函数
梯度计算公式 = (后 - 前)/二者距离 多维数组返回第一个数组为最外层梯度,上第一数组中的第一个1表示(17-16)/1 下边一个数组为第二层维度梯度 如其中-3 = (14-17)/1 #14与17两数距离为1 1.5 = (19-16)/2 #不出于边缘,则用上下两个数来求梯度
官方文档
https://www.numpy.org.cn/reference/
Matplotlib
介绍
数据可视化
引用
plt.plot()
只有一个一维数据则默认为X轴,纵轴为其索引
format_string为曲线格式字符串
曲线颜色
曲线类型
精细控制
点标记
例
简易控制版 第一条曲线为 green绿色 实心五角标记 实线曲线 第二条曲线为 yellow黄色 实心方块标记 虚线曲线 第三条曲线为 red红色 X标记 无连线
a为列表形式的数字[1,2,3,4,5,6,7,8,9]
显示图片
plt.imshow(image)
保存
plt.savefig("文件名",dpi=600) dpi 为图像质量
横纵坐标范围控制
plt.axis([-1,10,0,6]) x轴范围为[-1,10] y轴范围为[0,6]
中文显示
全局字体风格和大小统一的情况下
实行全局控制
rcParams参数
字体选项
字体风格和大小不能统一的情况下
在有中文输出的地方增加 fontproperties="Kaiti",fontsize=20
描述信息函数
注解函数详解
s = 注解文本 xy = 箭头坐标 xytext = 文本坐标 arrowprops = 箭头属性
facecolor 控制箭头颜色 shrink 控制箭头两侧的空白比例 width 箭头宽度
text与title例
示例
多绘图区域
简易版
复杂区域
单独指定模式
(3,3) = 网格形状 (1,0) = 选择索引为(1,0)的那一格 colspan = 2 横向占用总共为2格
索引指定模式
选什么图表达数据
常用图
百分比表达选饼图
labels为区域名称 sizes为对应区域大小 explode为突出值 autopct为百分数的格式 startangle为起始角度
控制图为正圆形饼图
看数据分布选直方图
30 为直方图个数 normed 为1时 Y轴为出现概率 为0时 Y轴为出现次数 alpha 为尺寸比例
柱状图
X = [2002,2003,2004,2005,2006,2007,2008,2009, 2010,2011,2012,2013,2014,2015] Y = [1, 3, 4, 3, 10, 20, 36, 51, 84, 146, 183, 219, 170, 22]) for i in range(len(X)): plt.bar(X[i],Y[i])
角度相关极坐标图
散点图
a[0,20)整数 维度为30,即30个整数 b[20,90)整数 维度为30
等高线
plt.contour([x,y],z,[leavels],**kwargs)
参数: X,Y :值Z的坐标。 X和Y必须都是2-D,且形状与Z相同,或者它们必须都是1-d,这样len(X)== M是Z中的列数,len(Y)== N是Z中的行数。 Z : 绘制轮廓的高度值。 levels: int或类数组,确定轮廓线/区域的数量和位置
绘制参数为Π的曲线
文档地址
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot
Pandas
创建二维数据
array创建
字典创建
DataFrame创建
直接指定行列索引
数据处理实际应用(增加可读性)
x_data = DataFrame(x_data, columns=['花萼长度', '花萼宽度', '花瓣长度', '花瓣宽度'])
列名对齐
pd.set_option('display.unicode.east_asian_width', True) # 设置列名对齐
读取写出
读取函数
pd.read_csv() 从文件,URL、文件型对象加载带分隔符的数据,默认分隔符为逗号 pd.read_table() 从文件、URL、稳健性对象加载带分隔符的数据,默认分隔符为制表符“\t” pd.read_fwf() 读取定宽列格式数据,即:无分隔符 pd.read_clipboard() 读取粘贴板数据
JSON文件处理
python标准库读取
import json data = json.load(文件名)
例
pandas读取与存储
读
data = pd.read_json("文件名。格式")
存
data.to_json("文件名.格式")
读存的排列参数orient
元数据 data = pd.DataFrame([["a","b"],["c","d"]],index=["row1","row2"],columns=["col1","col2"])
行优先展示
列优先展示
只有值
下载数据并保存为JSON文件代码
if not os.path.exists('train.json'): trainData = requests.get("https://worksheets.codalab.org/rest/bundles/0x0161fd2fb40d4dd48541c2643d04b0b8/contents/blob/") with open("train.json", "wb") as f: f.write(trainData.content) if not os.path.exists('test.json'): testData = requests.get("https://worksheets.codalab.org/rest/bundles/0x1f96bc12222641209ad057e762910252/contents/blob/") with open("test.json", "wb") as f: f.write(testData.content) #读取数据至DataFrame中 train_df = pd.read_json("train.json").transpose() test_df = pd.read_json("test.json").transpose()
pd.read_csv( )参数详解
1.filepath_or_buffer:(这是唯一一个必须有的参数,其它都是按需求选用的) 文件所在处的路径 2.sep: 指定分隔符,默认为逗号’,’ 3.delimiter : str, default None 定界符,备选分隔符(如果指定该参数,则sep参数失效) 4.header:int or list of ints, default ‘infer’ 指定哪一行作为表头。默认设置为0(即第一行作为表头),如果没有表头的话,要修改参数,设置header=None 5.names: 指定列的名称,用列表表示。一般我们没有表头,即header=None时,这个用来添加列名就很有用啦! 6.index_col: 指定哪一列数据作为行索引,可以是一列,也可以多列。多列的话,会看到一个分层索引 7.prefix: 给列名添加前缀。如prefix=“x”,会出来"x1"、“x2”、"x3"酱纸 8.nrows : int, default None 需要读取的行数(从文件头开始算起) 9.encoding: 乱码的时候用这个就是了,官网文档看看用哪个: https://docs.python.org/3/library/codecs.html#standard-encodings 10.skiprows : list-like or integer, default None 需要忽略的行数(从文件开始处算起),或需要跳过的行号列表(从0开始)。
写出
写出内容.to_csv("文件名.格式") 例: data.to_csv("训练集.txt")
df = pd.read_csv('property-data.csv',encoding="gbk") #引号里的内容格式 :路径+ 文件名 + 格式
索引
行索引
列索引
值索引
取值要 列索引+行索引 (顺序不对索引不了)
新增行列
x_data['类别'] = y_data # 新加一列,列标签为‘类别’,数据为y_data
整数索引iloc
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html?highlight=iloc#pandas.DataFrame.iloc
位置索引loc
索引重新定义
参数
重排
利用index columns调整结构
增减行列/填充元素
删除0轴第1个索引 在1轴第2个位置增加“新增”索引 6填充空格
修改索引
数据类型操作
元素填充
零填充
df.fillna(0)
字符串填充
df.fillna("missing")
前一个数据填充
df.fillna(method="pad")
后一个数据填充和限制每列替换数目
df.fillna(method="bfill",limit=1)
具体值填充
与另一个数组交互
查看所有列和行
元素定位
# 先找到在哪行 df[ df['order_id'].isin(['17592719302995']) ] # loc填入行号,此时就能判断所在列 df.columns[df.loc[1].isin([17592719302995])]
删除元素
删除多个对象要用[ ]包起来,删除1轴要特别指定,因为默认操作0轴
去除重复行
all_features.drop_duplicates(subset=None, keep='first', inplace=False) #去除重复的行 inplace开了就是在原数据上操作
缺失值处理
每个元素检查
train.isnull()
每列检查
train.isnull().any()
定位缺失位置
df[df.isnull().values==True]
统计缺失值数量
df.isnull( ).sum( )
去除缺失值并重置索引
data.dropna(axis = 0,inplace = True) #去除Null值,且在原数据上操作
all_features.reset_index(drop=True, inplace=True) #重置一下索引,且把之前索引丢掉,而且在原数居上操作,因为去除行会把对应索引去掉
数组连接
C = pd.concat((A,B))
异常值处理
具体业务法
完整代码
# 异常值:远离正常范围的错误的值 ---剔除 # 离群值:远离正常范围的正确的值 # 判定并剔除 # 1、具体业务法 # 根据自己对具体业务的理解,设定阈值,再去进行判断 # 以初中生的年龄为例 --->[12,16] def juti_yewu(data): """ 根据具体业务来剔除异常值 :param data: 需要剔除异常值的数据series :return: bool数组 """ # 确定上限 up = 16 # 确定下限 low = 12 # 判断 mask1 = data <= up # 与上限进行对比 mask2 = data >= low # 与下限进行对比 # 求 & --->and mask = mask1 & mask2 return mask # # # 创建df df = pd.DataFrame(data={ 'name': ['zs', 'ls', 'ww', 'zl'], 'age': [12, 16, 18, 9] }) print('df:\n', df) # # 调用 mask = juti_yewu(df['age']) print('mask:\n', mask) # # 筛选 df = df.loc[mask, :] print('剔除异常值之后的结果为:\n', df)
3σ原则
3σ原则又称为拉依达法则。该法则就是先假设一组检测数据只含有随机误差,对原始 数据进行计算处理得到标准差,然后按一定的概率确定一个区间,认为误差超过这个区间的就属于异常值 这种判别处理方法仅适用于对正态或近似正态分布的样本数据进行处理,如下表所示, 其中σ代表标准差,μ代表均值,x=μ为图形的对称轴 数据的数值分布几乎全部集中在区间(μ-3σ,μ+3σ)内,超出这个范围的数据仅占不 到 0.3%,故根据小概率原理,可以认为超出 3σ的部分数据为异常数据
完整代码
# 2、3sigma原则 # 正态分布的 推论 ---> 99.73%的数据 (u-3a,u+3a)之间 ,拆过这个区间剩下的0.27%为异常值 def three_sigma(data): """ 基于3sigma原则进行剔除异常值 :param data: 需要剔除异常值的数据series :return: bool数组 """ # 确定上限 # u + 3a up = data.mean() + 3 * data.std() # 确定下限 low = data.mean() - 3 * data.std() # 比较 mask1 = data < up mask2 = data > low # 求 & mask = mask1 & mask2 return mask
箱线图
完整代码
# 3、箱线分析法 # 箱线图 ---四分位数指标 # 正常值的范围在 (ql-1.5iqr,qu+1.5iqr)----> 超过该区间则可认为为异常值 # ql --->下四分位数 # qu --->上四分位数 # iqr ---->四分位间距 ---> qu -ql def box_analysis(data): """ 基于箱线分析法来剔除异常值 :param data: 需要剔除异常值的数据series :return: bool数组 """ # 确定qu qu = data.quantile(q=0.75) # 确定ql ql = data.quantile(q=0.25) # 确定iqr iqr = qu - ql # 确定上限 up = qu + 1.5 * iqr # 确定下限 low = ql - 1.5 * iqr # 比较 mask1 = data < up mask2 = data > low # 求 & mask = mask1 & mask2 return mask
文章链接
https://blog.csdn.net/markshui/article/details/108214227?ops_request_misc=&request_id=&biz_id=102&utm_term=pandas%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86%E7%A6%BB%E7%BE%A4%E7%82%B9&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-2-108214227.pc_search_mgc_flag&spm=1018.2226.3001.4187
察看每行列的类别数
察看行
所有列和特定列
查看数据大小和类型
函数:data.info( )
遍历行
1. pd.iterrows()函数 for index, row in df.iterrows():
运算
法则
零维:一个数
加减乘除例
多维数据相乘
多维与一维 发生在1轴 若想发生在0轴,需用方法实现
c 直接作用于a的1轴 1=1+0 3=1+2 第二行也是
方法实现
加减乘除实现
普通实现+-*/
方法实现(可填充值)
值填充到不能参加运算的数组行列 如上9填充到a0轴的第三列 9+15=24
比较运算
多维比较(要求同维度)
多维与一维(默认1轴,广播运算)
平方运算power()
数组不可以直接**
排序
索引排序
默认0轴,升序情况下 0轴的bac索引已排序为abc
数值排序
Series排序
DataFrames排序
NaN统一放于末尾
基本统计
单项统计
默认0轴
全面统计
累计统计
滚动计算(相邻值计算)
横轴上,即行方向 两个元素就计算其和
前n个数运算
默认0轴方向
按照0轴方向,即一列上前n个数的最大值
相关分析
协方差判定(并不精确)
皮尔森系数
r的取值在-1与+1之间,若r>0,表明两个变量是正相关,即一个变量的值越大,另一个变量的值也会越大;若r<0,表明两个变量是负相关,即一个变量的值越大另一个变量的值反而会越小。r 的绝对值越大表明相关性越强,要注意的是这里并不存在因果关系。若r=0,表明两个变量间不是线性相关,但有可能是其他方式的相关(比如曲线方式)
代码实现
两个都是一维
官方技术文档
https://pandas.pydata.org/pandas-docs/stable/reference/index.html
其它
介绍
一维Series类型
介绍
自定义索引
作为第二个参数,可以省略index=
创建
标量创建
字典创建
Index指定结构创建
ndarray创建
列表创建
操作
获取索引/数据值
索引
单值索引
自定义索引和自动索引并存
多值索引
再加一个[ ]
条件索引
切片
索引判定
类似字典
对齐
只会留下相同索引值
Series对象命名
修改值
类似字典,直接赋值即可
二维多维DataFrame
定义
自然语言处理
jieba分词库
安装
原理
三种模式(输入=str 输出=list)
wordcloud词云库
介绍
文本变词云
基本原理(接受分类器)
加载文本 输出图像
流程
内部流程
wordcloudWordCloud()参数
图像长宽
字体大小
字体~最大单词数~排除列表
词云形状~背景色
tensorflow
安装
参考文章
https://blog.csdn.net/weixin_44170512/article/details/103990592
报错处理
错:twisted 18.7.0 requires PyHamcrest>=1.9.0, which is not installed.
解:pip install PyHamcrest -i https://pypi.tuna.tsinghua.edu.cn/simple
缺什么安装什么
流程
CUDA安装
CUDA软件安装
cuDNN神经网络加速库安装
配置环境变量
TensorFlow安装
pip install -U tensorflow-gpu -i https://pypi.tuna.tsinghua.edu.cn/simple
新版安装
tf下载命令(豆瓣快) pip install tensorflow==2.1 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
经典实例代码
鸢尾花数据分类
流程
神经网络结构
实敲
# 利用鸢尾花数据集,实现前向传播、反向传播,可视化loss曲线 # 导入所需模块 import tensorflow as tf from sklearn import datasets from matplotlib import pyplot as plt import numpy as np # 导入数据,分别为输入特征和标签 x_data = datasets.load_iris().data y_data = datasets.load_iris().target # 随机打乱数据(因为原始数据是顺序的,顺序不打乱会影响准确率) # seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样(为方便教学,以保每位同学结果一致) np.random.seed(116) # 使用相同的seed,保证输入特征和标签一一对应 np.random.shuffle(x_data) np.random.seed(116) np.random.shuffle(y_data) tf.random.set_seed(116) # 将打乱后的数据集分割为训练集和测试集,训练集为前120行,测试集为后30行 x_train = x_data[:-30] y_train = y_data[:-30] x_test = x_data[-30:] y_test = y_data[-30:] # 转换x的数据类型,否则后面矩阵相乘时会因数据类型不一致报错 x_train = tf.cast(x_train, tf.float32) x_test = tf.cast(x_test, tf.float32) # from_tensor_slices函数使输入特征和标签值一一对应。(把数据集分批次,每个批次batch组数据) train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32) test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) # 生成神经网络的参数,4个输入特征故,输入层为4个输入节点;因为3分类,故输出层为3个神经元 # 用tf.Variable()标记参数可训练 # 使用seed使每次生成的随机数相同(方便教学,使大家结果都一致,在现实使用时不写seed) w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1)) b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1)) lr = 0.1 # 学习率为0.1 train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据 test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据 epoch = 500 # 循环500轮 loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和 # 训练部分 for epoch in range(epoch): #数据集级别的循环,每个epoch循环一次数据集 for step, (x_train, y_train) in enumerate(train_db): #batch级别的循环 ,每个step循环一个batch with tf.GradientTape() as tape: # with结构记录梯度信息 y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算 y = tf.nn.softmax(y) # 使输出y符合概率分布(此操作后与独热码同量级,可相减求loss) y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方误差损失函数mse = mean(sum(y-out)^2) loss_all += loss.numpy() # 将每个step计算出的loss累加,为后续求loss平均值提供数据,这样计算的loss更准确 # 计算loss对各个参数的梯度 grads = tape.gradient(loss, [w1, b1]) # 实现梯度更新 w1 = w1 - lr * w1_grad b = b - lr * b_grad w1.assign_sub(lr * grads[0]) # 参数w1自更新 b1.assign_sub(lr * grads[1]) # 参数b自更新 # 每个epoch,打印loss信息 print("Epoch {}, loss: {}".format(epoch, loss_all/4)) train_loss_results.append(loss_all / 4) # 将4个step的loss求平均记录在此变量中 loss_all = 0 # loss_all归零,为记录下一个epoch的loss做准备 # 测试部分 # total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0 total_correct, total_number = 0, 0 for x_test, y_test in test_db: # 使用更新后的参数进行预测 y = tf.matmul(x_test, w1) + b1 y = tf.nn.softmax(y) pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类 # 将pred转换为y_test的数据类型 pred = tf.cast(pred, dtype=y_test.dtype) # 若分类正确,则correct=1,否则为0,将bool型的结果转换为int型 correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32) # 将每个batch的correct数加起来 correct = tf.reduce_sum(correct) # 将所有batch中的correct数加起来 total_correct += int(correct) # total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数 total_number += x_test.shape[0] # 总的准确率等于total_correct/total_number acc = total_correct / total_number test_acc.append(acc) print("Test_acc:", acc) print("--------------------------") # 绘制 loss 曲线 plt.title('Loss Function Curve') # 图片标题 plt.xlabel('Epoch') # x轴变量名称 plt.ylabel('Loss') # y轴变量名称 plt.plot(train_loss_results, label="$Loss$") # 逐点画出trian_loss_results值并连线,连线图标是Loss plt.legend() # 画出曲线图标 plt.show() # 画出图像 # 绘制 Accuracy 曲线 plt.title('Acc Curve') # 图片标题 plt.xlabel('Epoch') # x轴变量名称 plt.ylabel('Acc') # y轴变量名称 plt.plot(test_acc, label="$Accuracy$") # 逐点画出test_acc值并连线,连线图标是Accuracy plt.legend() plt.show()
基础知识区
tensorflow介绍
它是什么
用数据流图用于数值计算且支持多平台的工具
特性
1.高灵活性 2.可移植性 3.产品和科研结合 4.自动求微分 5.多语言支撑 6.性能最优化
架构
开发流程
核
keras
介绍
tf.keras
联系
区别
选择
人工智能三学派
行为主义
基于控制论 目的:构建感知—动作控制系统 (控制如平衡、行走、避障等自适应控制系统)
符号主义
基于算数逻辑表达式 流程:求解问题先把问题描述为表达式, 再求解表达式 目的:实现理性思维,构建专家系统
连接主义
基于仿生学,模仿神经元链接关系 目的:实现感性思维,如神经网络
神经网络MP模型
两位科学家将大脑的计算方式归纳为MP模型 特征,然后求和
神经网络复杂度NN
空间复杂度: 层数 = 隐藏层 + 1个输出层 下图为2层 总参数 = 总W +总b 下图第一层:3*4(W) + 4(b) 第二层:4*2(W) + 2(b) 共26
时间复杂度: 定义:乘加运算次数(权重线个数) 下图 3*4 + 4*2 = 20
指数衰减学习率
代码实敲
import tensorflow as tf w = tf.Variable(tf.constant(5, dtype=tf.float32)) epoch = 40 LR_BASE = 0.2 # 最初学习率 LR_DECAY = 0.99 # 学习率衰减率 LR_STEP = 1 # 喂入多少轮BATCH_SIZE后,更新一次学习率 for epoch in range(epoch): # for epoch 定义顶层循环,表示对数据集循环epoch次,此例数据集数据仅有1个w,初始化时候constant赋值为5,循环100次迭代。 lr = LR_BASE * LR_DECAY ** (epoch / LR_STEP) with tf.GradientTape() as tape: # with结构到grads框起了梯度的计算过程。 loss = tf.square(w + 1) grads = tape.gradient(loss, w) # .gradient函数告知谁对谁求导 w.assign_sub(lr * grads) # .assign_sub 对变量做自减 即:w -= lr*grads 即 w = w - lr*grads print("After %s epoch,w is %f,loss is %f,lr is %f" % (epoch, w.numpy(), loss, lr))
应用
先用较大学习率,快速得到较优解,然后逐步减小学习率,使模型在后期稳定 这样会节省迭代时间
过拟合与欠拟合
子主题
激活函数
sigmoid
tf.nn.sigmoid(x)

Tanh
tf.math.tanh(x)

relu
tf.nn.relu(x)
 注:dead情况是 激活值为负数时,梯度 = 0,意味着不更新,也就是神经元死亡 解决: 1.改变随机初始化,避免过多负数送入relu函数 2.减少学习率,减少参数的巨大变化,避免训练中产生过多负数进入relu
leeky relu
tf.nn.leaky_relu(x)
专为解决负数过多设计的
建议
损失函数
均方误差MSE loss_mse = tf.reduce_mean(tf.square(y_-y))

ce(Cross Entropy)交叉熵
标准版: tf.losses.categorical_crossentropy(y_,y)

softmax版: tf.nn.softmax_cross_entropy_with_logits(y_,y)

自定义损失函数
子主题
sklearm中的三种误差
from sklearn.metrics import mean_squared_error, mean_absolute_error #引入模块 # calculate MSE 均方误差 ---> E[(预测值-真实值)^2] (预测值减真实值求平方后求均值) mse = mean_squared_error(predicted_stock_price, real_stock_price) # calculate RMSE 均方根误差--->sqrt[MSE] (对均方误差开方) rmse = math.sqrt(mean_squared_error(predicted_stock_price, real_stock_price)) # calculate MAE 平均绝对误差----->E[|预测值-真实值|](预测值减真实值求绝对值后求均值) mae = mean_absolute_error(predicted_stock_price, real_stock_price)
优化器
总纲 1.计算 t 时刻损失函数关于当前参数的梯度g 2.计算 t 时刻一阶动量 m 和二阶动量 V 3.计算 t 时刻下降梯度 n = lr * m/(v**0.5) 4.计算 t + 1 时刻参数 w = w - n
SGD 描述:随机梯度下降 m = g v = 1 n = lr * g w = w - lr * g
代码
w1.assign_sub(lr * grads[0]) # 参数w1自更新 b1.assign_sub(lr * grads[1]) # 参数b自更新 等等 参数
SGDM 描述:在SGD上增加一阶动量 #m表示各时刻梯度方向的指数滑动平均值 β默认0.9
代码
m_w,m_b = 0,0 #初始值都要设置为0 beta = 0.9 #默认比较好的参数 m_w = beta * m_w + (1 - beta) * grads[0] m_b = beta * m_b + (1 - beta) * grads[1] w1.assign_sub(lr * m_w) b1.assign_sub(lr * m_b)
Adagrad 描述:在SGD基础上增加二阶动量 #v 是从开始到现在,梯度累计的平方和
代码
v_w,v_b = 0,0 # adagrad v_w += tf.square(grads[0]) v_b += tf.square(grads[1]) w1.assign_sub(lr * grads[0] / tf.sqrt(v_w)) b1.assign_sub(lr * grads[1] / tf.sqrt(v_b))
RMSP 描述:SGD基础上增加二阶动量 #v :计算方式 → 指数滑动平均值计算 表征 → 过去一段时间的平均值
代码
v_w , v_b = 0,0 beta = 0.9 # rmsprop v_w = beta * v_w + (1 - beta) * tf.square(grads[0]) v_b = beta * v_b + (1 - beta) * tf.square(grads[1]) w1.assign_sub(lr * grads[0] / tf.sqrt(v_w)) b1.assign_sub(lr * grads[1] / tf.sqrt(v_b))
Adam 描述:一阶动量和二阶动量相结合 默认值 β1 = 0.9 β2 = 0.999
代码
m_w , m_b = 0 , 0 v_w , v_b = 0 , 0 beta1 , beta2 = 0 , 0 delta_w , delta_b = 0 , 0 global_step = 0 #训练部分 双层循环 global_step += 1 with结构 # adam #动量计算部分 m_w = beta1 * m_w + (1 - beta1) * grads[0] m_b = beta1 * m_b + (1 - beta1) * grads[1] v_w = beta2 * v_w + (1 - beta2) * tf.square(grads[0]) v_b = beta2 * v_b + (1 - beta2) * tf.square(grads[1]) #修正部分 m_w_correction = m_w / (1 - tf.pow(beta1, int(global_step))) m_b_correction = m_b / (1 - tf.pow(beta1, int(global_step))) v_w_correction = v_w / (1 - tf.pow(beta2, int(global_step))) v_b_correction = v_b / (1 - tf.pow(beta2, int(global_step))) #更新部分 w1.assign_sub(lr * m_w_correction / tf.sqrt(v_w_correction)) b1.assign_sub(lr * m_b_correction / tf.sqrt(v_b_correction))
基础函数区
Tensor张量
介绍
张量:多维数组(列表) 阶:张量的维数 判断阶数看 [ 有几个,几个就是几阶
数据类型
创建
直接创建
tf.constant(张量内容,dtype=数据类型(可选))
shape()中逗号隔开几个数字,就是几维张量
NP转化
tf.convert_to_tensor(数据名,dtype=数据类型)
numpy格式转化
创建全部为m的数组
tf.zeros(维度)全0 tf.ones(维度)全1 tf.fill(维度,指定值K)全K
维度注意
实例
随机初始化数组
正态分布随机数 tf.random.normal(维度,mean=均值,stddev=标准差)
正态分布的随机数(随机数更集中一些) tf.random.truncated_normal(维度,mean=均值,stddev=标准差)
子主题
均匀分布随机数 范围:【min,max) tf.ranom.uniform(维度,minval=最小值,maxval=最大值)
常用函数
基本数学运算
+ : tf.add(x,y) - : tf.subtract(x,y) * : tf.multiply(x,y) / : tf.divide(x,y) (需要维度相同) 平方: tf.square(x) n次方: tf.pow(x,n) 开方: tf.sqrt(x) 矩阵乘:tf.matmul(x,y) 类似dot
转化类型/最大最小值
强制转换张量数据类型 tf.cast(张量名,dtype=数据类型)
计算张量维度上元素的最小值 tf.reduce_min(张量名)
计算张量维度上元素的最大值 tf.reduce_max(张量名)
指定维度平均值/和
指定维度平均值 tf.reduce_mean(张量名,axis=轴)
指定维度和 tf.reduce_sum(张量名,axis=轴)
Variable
可训练参数Variable tf.Variable() 将变量标记为可训练 被标记的变量会在反向传播中记录梯度信息 常用于标记带训练参数 w = tf.Variable(初始值)
特征标签配对
函数体 dataset = tf.data.Dataset.from_tensor_slices((features, labels))
求导
tf.GradientTape()
格式: with tf.GradientTape() as tape: 若干计算过程 grad = tape.gradient(函数, 对谁求导)
枚举
seq = ['one', 'two', 'three'] for i, element in enumerate(seq): print(i, element) # i 接收索引 element接收元素
可以枚举每个元素并配上索引号,常在for循环中使用
独热编码
tf.one_hot(待转换数据,几分类)
softmax
tf.nn.softmax(y) 使输出符合概率分布
自更新
w = tf.Variable(4) #要先变为可训练类型 w.assign_sub(1) #等价于w-=1 即 w = w-1
某维度最大值的索引
tf.argmax(张量名,axis=操作轴)
axis理解
=0 纵向操作 =1 横向操作 不指定 全部元素参与计算
条件语句
条件where
tf.where(条件语句,真返回A,假返回B)
tf.greater(a,b)指判断a,b各维度大小
网络八股
六步法提纲Sequential
import #引入模块 train,test #告知训练集、测试集 model = tf.keras.models.Sequential #网络结构(前向传播) model.compile #优化器、损失函数、评测指标选择 model.fit #训练 告知test和train特征和标签、batch、迭代次数 model.summary #打印出网络的结构和参数统计
Sequential(连续的)结构设置
model = tf.keras.models.Sequential(网络结构)#描述各层网络
结构举例
拉直层: tf.keras.layers.Flatten() #不含计算,只是形状转换 输入:特征 输出:拉直后的一维数组
全连接层: tf.keras.layers.Dense(神经元个数,activation = "激活函数", kernl_regularizer = "正则化类型") activation(字符串给出)可选:relu、softmax、sigmoid、tanh、 kernel_regularizer 可选:tf.keras.regularizers.l1()、tf.keras.regularizers.l2()
卷积层: tf.keras.layers.Conv2D(filters = 卷积核个数,kernel_size = 卷积核尺寸 strides = 卷积步长,padding = "valid" or "same")
LSTM层: tf.keras.layers.LSTM()
compile(编制)设置
model.compile(optimizer = 优化器,loss = 损失函数,metrics = ["准确率"])
优化器可选
字符串类参数
"sgd" "adagrad" "adadelta" "adam"
精细控制类参数
tf.keras.optimizers.SGD(lr = 学习率,momentum = 动量参数) tf.keras.optimizers.Adagrad(lr = 学习率) tf.keras.optimizers.Adadelta(lr = 学习率) tf.keras.optimizers.Adam(lr = 学习率,beta_1 = 0.9, beta_2 = 0.999)
loss可选
字符串类
"mes" "sparse_categorical_crossentropy"
精细控制类
tf.keras.losses.MeanSquaredError() tf.keras.losses.SparseCategoricalCrossentropy(from_logits = False) #False = 经过概率分布(如softmax)的输出 Ture = 没有经过概率分布的输出 #应用提示:如果在十分类问题上正确率只有1/10,很有可能是这个参数错了
metrics评测指标
字符串类
"accuracy" : y_真实答案和y预测答案都是数值,如y_1 = [1] y = [1] "categorical_accuracy" : y_和y都是独热码(概率分布) #绝对准确率 "sparse_categorical_accuracy": y_是数值,y是独热码(概率分布)
fit 训练设置
model.fit(训练集输入特征,训练集的标签,batch_size = , epoch = , validation_data =(测试集的输入特征,测试集的标签), validation_split = 从训练集划分多少比例给测试集,#data和split 二者选一 validation_freq = 多少次epoch用测试集测试一次)
详细参数
fit( x, y, batch_size=32, epochs=10, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0)
summary总览
model.summary()
代码示例 (鸢尾花预测)
import tensorflow as tf from sklearn import datasets import numpy as np #第一步 x_train = datasets.load_iris().data y_train = datasets.load_iris().target #第二步 np.random.seed(116) np.random.shuffle(x_train) np.random.seed(116) np.random.shuffle(y_train) tf.random.set_seed(116)#数据乱序 model = tf.keras.models.Sequential([ tf.keras.layers.Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2()) ]) #第三步 model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy'])#上层用了softmax 所以这是False #第四步 model.fit(x_train, y_train, batch_size=32, epochs=500, validation_split=0.2, validation_freq=20) #第五步 model.summary() #第六步
特点:上层输出就是下层输入
class八股
特点:可以带有跳连的非顺序网络结构
import train,test class MyModel(Model)model = MyModel model.compile model.fit model.summary
类框架代码
class MyModel(Model):#表示继承了TF的Model类 def _init_(self):#准备积木 super(MyModel,self)._init_() 定义网络结构块 def call(self,x):#调用积木 调用网络结构块,实现前向传播 return y model = MyModel()
八股增强功能
自制数据集
应用场景:本领域的数据集加载与处理
实例代码
import numpy as np import os import tensorflow as tf from PIL import Image #给定各种数据的存放位置 train_path = './mnist_image_label/mnist_train_jpg_60000/' train_txt = './mnist_image_label/mnist_train_jpg_60000.txt' x_train_savepath = './mnist_image_label/mnist_x_train.npy' y_train_savepath = './mnist_image_label/mnist_y_train.npy' test_path = './mnist_image_label/mnist_test_jpg_10000/' test_txt = './mnist_image_label/mnist_test_jpg_10000.txt' x_test_savepath = './mnist_image_label/mnist_x_test.npy' y_test_savepath = './mnist_image_label/mnist_y_test.npy' #数据集制作函数 def generateds(path,txt): f = open(txt,"r")#只读模式打开txt文本类型的原始数据 contents = f.readlines()#内容 = 读入所有行,每行为元素 f.close() #关闭文件避免占用资源 x,y_ = [],[]#准备好x_train和y_train存放的地方 for content in contents:#遍历每一行 value = content.split()#空格分开图片名和标签 img_path = path + value[0]#该图的索引路径=图片路径+图片名 img = Image.open(img_path)#读入图片 img = np.array(img.convert("L"))#图片变为8位宽度的灰度值 img = img/255 #数据归一化 x.append(img)#加入列表x y_.append(value[1])#标签加入列表y_ print("loading:"+content)#打印状态提示 x = np.array(x) y_ = np.array(y_) y_ = y_.astype(np.int64) return x,y_ #判定如果已存在制作好的数据集 则直接读取,没有的话就根据txt制作数据集 if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists( x_test_savepath) and os.path.exists(y_test_savepath): print('-------------Load Datasets-----------------') x_train_save = np.load(x_train_savepath) y_train = np.load(y_train_savepath) x_test_save = np.load(x_test_savepath) y_test = np.load(y_test_savepath) x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28)) x_test = np.reshape(x_test_save, (len(x_test_save), 28, 28)) else: print('-------------Generate Datasets-----------------') x_train, y_train = generateds(train_path, train_txt) x_test, y_test = generateds(test_path, test_txt) print('-------------Save Datasets-----------------') x_train_save = np.reshape(x_train, (len(x_train), -1)) x_test_save = np.reshape(x_test, (len(x_test), -1)) #-1代表让程序自己根据原来的维度和给定的维度len(x_train)来判断剩余维度 np.save(x_train_savepath, x_train_save) np.save(y_train_savepath, y_train) np.save(x_test_savepath, x_test_save) np.save(y_test_savepath, y_test) #TF深度学习部分 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1) model.summary()
数据增强
应用场景:在数据集不够的情况下进行得到数据扩充
实例代码
import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) # 给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 28, 28, 1),是数据和网络结构匹配 image_gen_train = ImageDataGenerator( rescale=1. / 1., # 如为图像,分母为255时,可归至0~1 rotation_range=45, # 随机45度旋转 width_shift_range=.15, # 宽度偏移 height_shift_range=.15, # 高度偏移 horizontal_flip=False, # 水平翻转 zoom_range=0.5 # 将图像随机缩放阈量50% ) image_gen_train.fit(x_train) model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test), validation_freq=1)#将增强后的数据以flow形式按照batch打包后训练 model.summary()
关键函数
image_gen_train = ImageDataGenerator( rescale=1. / 1., #数据归一化, 如为图像,分母为255时,可归至0~1 rotation_range=45, # 随机45度旋转 width_shift_range=.15, # 宽度偏移 height_shift_range=.15, # 高度偏移 horizontal_flip=False, # 水平翻转 zoom_range=0.5 # 将图像随机缩放阈量50% ) image_gen_train.fit(x_train)
断点续训
应用场景:存取模型 介绍:在进行神经网络训练过程中由于一些因素导致训练无法进行,需要保存当前的训练结果下次接着训练
代码
import tensorflow as tf import os mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) checkpoint_save_path = "./checkpoint/mnist.ckpt"#路径+文件名 if os.path.exists(checkpoint_save_path + '.index'):#因为生成ckpt文件时候会生成索引表,所以通过判断是不是有了索引表,就可以判断有没有保存过模型参数了,如果有,就直接读取 print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True,#是否只保留模型参数 save_best_only=True)#是否只保留最优结果 history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary()
输出
参数提取
应用场景:刚刚保存的参数是多少,我想看看 过程: 把参数存入文本
 #为什么设置print输出格式? 因为不设置会有很多省略号
代码
#手写数字识别 + 断点续训 + 查看/保存参数 import tensorflow as tf import os import numpy as np np.set_printoptions(threshold=np.inf)#打印所有内容 mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) #断点续训 checkpoint_save_path = "./checkpoint/mnist.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True) history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary() #打印所有可训练参数 print(model.trainable_variables) #保存参数 file = open('./weights.txt', 'w') for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close()
acc/loss可视化
子主题
关键代码
# 显示训练集和验证集的acc和loss曲线 history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) acc = history.history['sparse_categorical_accuracy']#训练集准确率 val_acc = history.history['val_sparse_categorical_accuracy']#测试集准确率 loss = history.history['loss']#训练集损失 val_loss = history.history['val_loss']#测试集损失 plt.subplot(1, 2, 1)#分为1行两列并选中第一列 plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.title('Training and Validation Accuracy') plt.legend()#画出图例 plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.title('Training and Validation Loss') plt.legend() plt.show()
完整代码
import tensorflow as tf import os import numpy as np from matplotlib import pyplot as plt np.set_printoptions(threshold=np.inf) mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) checkpoint_save_path = "./checkpoint/mnist.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True) history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary() print(model.trainable_variables) file = open('./weights.txt', 'w') for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() ############################################### show ############################################### # 显示训练集和验证集的acc和loss曲线 acc = history.history['sparse_categorical_accuracy'] val_acc = history.history['val_sparse_categorical_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.title('Training and Validation Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.title('Training and Validation Loss') plt.legend() plt.show()
给图识物


代码
代码
from PIL import Image import numpy as np import tensorflow as tf model_save_path = './checkpoint/mnist.ckpt' model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax')]) model.load_weights(model_save_path) preNum = int(input("input the number of test pictures:"))#输入多少次识别任务 #数据预处理 for i in range(preNum): image_path = input("the path of test picture:") img = Image.open(image_path) img = img.resize((28, 28), Image.ANTIALIAS)#转化为神经网络能消化的尺寸28*28 img_arr = np.array(img.convert('L')) #颜色突出 因为训练时是黑底白字图,而现在输入则是白纸黑字图 for i in range(28):#双层循环,遍历每个像素点 for j in range(28): if img_arr[i][j] < 200:#像素值小于200的,设置为黑色 img_arr[i][j] = 255 else: img_arr[i][j] = 0 #img_arr = 255 - img_arr 或者采取这个颜色取反 img_arr = img_arr / 255.0#数据归一化 更适合神经网络计算 x_predict = img_arr[tf.newaxis, ...]#前边添加一个1维度,因为数据训练前都是按照batch送入网络 result = model.predict(x_predict)#输出softmax概率值 pred = tf.argmax(result, axis=1)#取最大值索引 print('\n') tf.print(pred) plt.pause(1) plt.close()
+1维度注释图 
反转注释图 
手写数字识别完整代码
总训练代码
#引入模块 import tensorflow as tf import os import numpy as np from matplotlib import pyplot as plt np.set_printoptions(threshold=np.inf)#设置打印参数无限多 #加载数据 mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 #网络结构 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) #模型配置 model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) #断点续训 checkpoint_save_path = "./checkpoint/mnist.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True) #训练 history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) #总结 model.summary() #print(model.trainable_variables) #保存参数 file = open('./weights.txt', 'w') for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() ############################################### show ############################################### #可视化 # 显示训练集和验证集的acc和loss曲线 acc = history.history['sparse_categorical_accuracy'] val_acc = history.history['val_sparse_categorical_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.title('Training and Validation Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.title('Training and Validation Loss') plt.legend() plt.show()
总应用代码
from PIL import Image import numpy as np import tensorflow as tf import matplotlib.pyplot as plt model_save_path = './checkpoint/mnist.ckpt' model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) model.load_weights(model_save_path) preNum = int(input("input the number of test pictures:"))#调用次数 for i in range(preNum): image_path = input("the path of test picture:")#输入图片位置和名字 img = Image.open(image_path)#打开图片 image = plt.imread(image_path) plt.set_cmap('gray') plt.imshow(image) img = img.resize((28, 28), Image.ANTIALIAS) img_arr = np.array(img.convert('L')) for i in range(28): for j in range(28): if img_arr[i][j] < 220: img_arr[i][j] = 255 else: img_arr[i][j] = 0 #img_arr = 255 - img_arr img_arr = img_arr / 255.0 x_predict = img_arr[tf.newaxis, ...] result = model.predict(x_predict) pred = tf.argmax(result, axis=1) print('\n') tf.print(pred) plt.pause(1) plt.close()
序列模型
循环核
介绍
特点: 参数时间共享,循环层提取时间信息 作用: 通过不同时刻的参数共享,实现对时间序列的信息提取
图示

计算过程

刷新状态
前向传播: 记忆体内存储的状态ht , 在每个时刻都被刷新 三个参数wxh,whh,why固定不变
反向传播: 三个参数矩阵wxh whh why被梯度下降法更新
时间步展开图
每个时刻记忆信息ht被刷新
循环神经网络
介绍
借助循环核提取时间特征后,送入全连接网络
层数=核数
TF rnn函数
F.循环计算层
tf.keras.layer.SimpleRNN(记忆体个数, activation = "激活函数", return_sequences = 是否每个时刻输出ht到下一层)
参数可选 activation = "激活函数"(不写,默认tanh) return_sequences = True 各时间步输出ht return_sequences =False 仅最后时间步输出ht(默认) 例:SimpleRNN(3,return_sequences = True)
True时的情况
False
x_train格式要求: [送入样本数,循环核时间展开步数,每个时间步输入特征个数]
例 解:图1 数据2样本 1时间步 每步3特征 图2 数据1样本 4时间步 每步2特征
计算过程图示
一个循环核的前向传播计算过程
实例代码
一对一预测
任务: 使模型在给出abcde五个字母中任意一个时,预测出它的下一个字母 如输入a,输出b,输入e,输出a
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense, SimpleRNN import matplotlib.pyplot as plt import os input_word = "abcde" w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} # 单词映射到数值id的词典 id_to_onehot = {0: [1., 0., 0., 0., 0.], 1: [0., 1., 0., 0., 0.], 2: [0., 0., 1., 0., 0.], 3: [0., 0., 0., 1., 0.], 4: [0., 0., 0., 0., 1.]} # id编码为one-hot x_train = [id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']]] y_train = [w_to_id['b'], w_to_id['c'], w_to_id['d'], w_to_id['e'], w_to_id['a']] #引导模型看到输入a,则输出b,看到b则输出c np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 使x_train符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。 # 此处整个数据集送入,送入样本数为len(x_train);输入1个字母出结果,循环核时间展开步数为1; 表示为独热码有5个输入特征,每个时间步输入特征个数为5 x_train = np.reshape(x_train, (len(x_train), 1, 5)) y_train = np.array(y_train) model = tf.keras.Sequential([ SimpleRNN(3), Dense(5, activation='softmax') ]) model.compile(optimizer=tf.keras.optimizers.Adam(0.01),#学习率为0.01 loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy'])#y_数值,y预测为独热码 #断点续训路径 checkpoint_save_path = "./checkpoint/rnn_onehot_1pre1.ckpt" #如果以前有训练过的参数则加载参数继续训练 if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='loss') # 由于fit没有给出测试集,不计算测试集准确率,根据loss,保存最优模型 history = model.fit(x_train, y_train, batch_size=32, epochs=100, callbacks=[cp_callback]) model.summary() # print(model.trainable_variables) file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() ############################################### show ############################################### # 显示训练集和验证集的acc和loss曲线 acc = history.history['sparse_categorical_accuracy'] loss = history.history['loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='Training Accuracy') plt.title('Training Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.title('Training Loss') plt.legend() plt.show() ############### predict ############# preNum = int(input("input the number of test alphabet:"))#输入次数 for i in range(preNum): alphabet1 = input("input test alphabet:")#输入字母 alphabet = [id_to_onehot[w_to_id[alphabet1]]]#字母变为机器能理解的独热码 # 使alphabet符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。此处验证效果送入了1个样本,送入样本数为1;输入1个字母出结果,所以循环核时间展开步数为1; 表示为独热码有5个输入特征,每个时间步输入特征个数为5 alphabet = np.reshape(alphabet, (1, 1, 5)) #因为是一个字母,所以1 #因为一步出结果,所以1 #因为独热码有五个热证,所以5 result = model.predict([alphabet])#装入列表进行预测 pred = tf.argmax(result, axis=1)#取概率值最大的那个下标 pred = int(pred)#变为整数类型 tf.print(alphabet1 + '->' + input_word[pred])#“abcde”中索引那个下标
词嵌入解决代码
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense, SimpleRNN, Embedding import matplotlib.pyplot as plt import os input_word = "abcde" w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} # 单词映射到数值id的词典 x_train = [w_to_id['a'], w_to_id['b'], w_to_id['c'], w_to_id['d'], w_to_id['e']] y_train = [w_to_id['b'], w_to_id['c'], w_to_id['d'], w_to_id['e'], w_to_id['a']] np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 使x_train符合Embedding输入要求:[送入样本数, 循环核时间展开步数] , # 此处整个数据集送入所以送入,送入样本数为len(x_train);输入1个字母出结果,循环核时间展开步数为1。 x_train = np.reshape(x_train, (len(x_train), 1))#送入5个样本,输入1个字母出结果 y_train = np.array(y_train)#变为np格式 #结构: model = tf.keras.Sequential([ Embedding(5, 2),#词汇表大小为5(abcde),2个数字表示一个字母 #上一行会生成一个[5,2]的可训练参数矩阵,实现编码可训练 SimpleRNN(3),#三个循环核 Dense(5, activation='softmax')#最终是五个字母的预测概率值 ]) #编制 model.compile(optimizer=tf.keras.optimizers.Adam(0.01), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) #断点续训 checkpoint_save_path = "./checkpoint/run_embedding_1pre1.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='loss') # 由于fit没有给出测试集,不计算测试集准确率,根据loss,保存最优模型 #训练 history = model.fit(x_train, y_train, batch_size=32, epochs=100, callbacks=[cp_callback]) #总结 model.summary() #存储参数 # print(model.trainable_variables) file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() ############################################### show ############################################### # 显示训练集和验证集的acc和loss曲线 acc = history.history['sparse_categorical_accuracy'] loss = history.history['loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='Training Accuracy') plt.title('Training Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.title('Training Loss') plt.legend() plt.show() ############### predict ############# preNum = int(input("input the number of test alphabet:")) for i in range(preNum): alphabet1 = input("input test alphabet:") alphabet = [w_to_id[alphabet1]] # 使alphabet符合Embedding输入要求:[送入样本数, 循环核时间展开步数]。 # 此处验证效果送入了1个样本,送入样本数为1;输入1个字母出结果,循环核时间展开步数为1。 alphabet = np.reshape(alphabet, (1, 1)) result = model.predict(alphabet) pred = tf.argmax(result, axis=1) pred = int(pred) tf.print(alphabet1 + '->' + input_word[pred])
多对一预测
任务:
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense, SimpleRNN import matplotlib.pyplot as plt import os input_word = "abcde" w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} # 单词映射到数值id的词典 id_to_onehot = {0: [1., 0., 0., 0., 0.], 1: [0., 1., 0., 0., 0.], 2: [0., 0., 1., 0., 0.], 3: [0., 0., 0., 1., 0.], 4: [0., 0., 0., 0., 1.]} # id编码为one-hot x_train = [ [id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']]], [id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']]], [id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']], id_to_onehot[w_to_id['a']]], [id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']], id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']]], [id_to_onehot[w_to_id['e']], id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']]], ] y_train = [w_to_id['e'], w_to_id['a'], w_to_id['b'], w_to_id['c'], w_to_id['d']] np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 使x_train符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。 # 此处整个数据集送入,送入样本数为len(x_train);输入4个字母出结果,循环核时间展开步数为4; 表示为独热码有5个输入特征,每个时间步输入特征个数为5 x_train = np.reshape(x_train, (len(x_train), 4, 5))#[5,4,5] #送入样本数 5个字母序列 #输入4个字母出结果 所以4 #每个时间步特征为5个 所以5 y_train = np.array(y_train) model = tf.keras.Sequential([ SimpleRNN(3),#循环核越多,记忆力越好,占用资源也越大 Dense(5, activation='softmax')#因为最终要5个字母的输出概率 ]) model.compile(optimizer=tf.keras.optimizers.Adam(0.01), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy'])#答案为数值,预测值为独热码 checkpoint_save_path = "./checkpoint/rnn_onehot_4pre1.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='loss') # 由于fit没有给出测试集,不计算测试集准确率,根据loss,保存最优模型 history = model.fit(x_train, y_train, batch_size=32, epochs=100, callbacks=[cp_callback]) model.summary() # print(model.trainable_variables) file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() ############################################### show ############################################### # 显示训练集和验证集的acc和loss曲线 acc = history.history['sparse_categorical_accuracy'] loss = history.history['loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='Training Accuracy') plt.title('Training Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.title('Training Loss') plt.legend() plt.show() ############### predict ############# preNum = int(input("input the number of test alphabet:")) for i in range(preNum): alphabet1 = input("input test alphabet:") alphabet = [id_to_onehot[w_to_id[a]] for a in alphabet1]#遍历这四个字母 # 使alphabet符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。此处验证效果送入了1个样本,送入样本数为1;输入4个字母出结果,所以循环核时间展开步数为4; 表示为独热码有5个输入特征,每个时间步输入特征个数为5 alphabet = np.reshape(alphabet, (1, 4, 5))#此时单字母样本送入,所以1 #4字母出结果,所以4 #每步5特征,所以5 result = model.predict([alphabet])#装入列表预测 pred = tf.argmax(result, axis=1) pred = int(pred) tf.print(alphabet1 + '->' + input_word[pred])

import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense, SimpleRNN, Embedding import matplotlib.pyplot as plt import os input_word = "abcdefghijklmnopqrstuvwxyz" w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25} # 单词映射到数值id的词典 training_set_scaled = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] x_train = [] y_train = [] for i in range(4, 26): x_train.append(training_set_scaled[i - 4:i]) y_train.append(training_set_scaled[i]) np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 使x_train符合Embedding输入要求:[送入样本数, 循环核时间展开步数] , # 此处整个数据集送入所以送入,送入样本数为len(x_train);输入4个字母出结果,循环核时间展开步数为4。 x_train = np.reshape(x_train, (len(x_train), 4)) y_train = np.array(y_train) model = tf.keras.Sequential([ Embedding(26, 2), SimpleRNN(10), Dense(26, activation='softmax') ]) model.compile(optimizer=tf.keras.optimizers.Adam(0.01), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['sparse_categorical_accuracy']) checkpoint_save_path = "./checkpoint/rnn_embedding_4pre1.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='loss') # 由于fit没有给出测试集,不计算测试集准确率,根据loss,保存最优模型 history = model.fit(x_train, y_train, batch_size=32, epochs=100, callbacks=[cp_callback]) model.summary() file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() ############################################### show ############################################### # 显示训练集和验证集的acc和loss曲线 acc = history.history['sparse_categorical_accuracy'] loss = history.history['loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='Training Accuracy') plt.title('Training Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='Training Loss') plt.title('Training Loss') plt.legend() plt.show() ################# predict ################## preNum = int(input("input the number of test alphabet:")) for i in range(preNum): alphabet1 = input("input test alphabet:") alphabet = [w_to_id[a] for a in alphabet1] # 使alphabet符合Embedding输入要求:[送入样本数, 时间展开步数]。 # 此处验证效果送入了1个样本,送入样本数为1;输入4个字母出结果,循环核时间展开步数为4。 alphabet = np.reshape(alphabet, (1, 4)) result = model.predict([alphabet]) pred = tf.argmax(result, axis=1) pred = int(pred) tf.print(alphabet1 + '->' + input_word[pred])
股票预测
F.获取实时股价
import tushare as ts import matplotlib.pyplot as plt df1 = ts.get_k_data('600519', ktype='D', start='2010-04-26', end='2020-04-26') datapath1 = "./SH600519.csv" df1.to_csv(datapath1)
任务:茅台数据股价预测 输入:60天的以往数据 输出:第61天的股票行情
普通RNN
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dropout, Dense, SimpleRNN import matplotlib.pyplot as plt import os import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, mean_absolute_error import math maotai = pd.read_csv('./SH600519.csv') # 读取股票文件 training_set = maotai.iloc[0:2426 - 300, 2:3].values # 前(2426-300=2126)天的开盘价作为训练集,表格从0开始计数,2:3 是提取[2:3)列,前闭后开,故提取出C列开盘价 test_set = maotai.iloc[2426 - 300:, 2:3].values # 后300天的开盘价作为测试集 # 归一化 sc = MinMaxScaler(feature_range=(0, 1)) #实例化 定义归一化:归一化到(0,1)之间 training_set_scaled = sc.fit_transform(training_set) # 求得训练集的最大值,最小值这些训练集固有的属性,并在训练集上进行归一化 test_set = sc.transform(test_set) # 利用训练集的属性对测试集进行归一化 x_train = [] y_train = [] x_test = [] y_test = [] # 测试集:csv表格中前2426-300=2126天数据 #做训练集 # 利用for循环,遍历整个训练集,提取训练集中连续60天的开盘价作为输入特征x_train,第61天的数据作为标签,for循环共构建2426-300-60=2066组数据。 for i in range(60, len(training_set_scaled)):#2126-60=2066次循环,所以生成2066组数据 x_train.append(training_set_scaled[i - 60:i, 0]) y_train.append(training_set_scaled[i, 0]) # 对训练集进行打乱 np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 将训练集由list格式变为array格式 x_train, y_train = np.array(x_train), np.array(y_train) # 使x_train符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。 # 此处整个数据集送入,送入样本数为x_train.shape[0]即2066组数据;输入60个开盘价,预测出第61天的开盘价,循环核时间展开步数为60; 每个时间步送入的特征是某一天的开盘价,只有1个数据,故每个时间步输入特征个数为1 x_train = np.reshape(x_train, (x_train.shape[0], 60, 1)) #做测试集 # 测试集:csv表格中后300天数据 # 利用for循环,遍历整个测试集,提取测试集中连续60天的开盘价作为输入特征x_train,第61天的数据作为标签,for循环共构建300-60=240组数据。 for i in range(60, len(test_set)): x_test.append(test_set[i - 60:i, 0]) y_test.append(test_set[i, 0]) # 测试集变array并reshape为符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数] x_test, y_test = np.array(x_test), np.array(y_test) x_test = np.reshape(x_test, (x_test.shape[0], 60, 1)) model = tf.keras.Sequential([ SimpleRNN(80, return_sequences=True),#80个循环核,各时间步输出记忆值ht Dropout(0.2),#随机失活 SimpleRNN(100), Dropout(0.2), Dense(1)#因为输出值第61天的开盘价只有一个数值,所以是1 ]) model.compile(optimizer=tf.keras.optimizers.Adam(0.001), loss='mean_squared_error') # 损失函数用均方误差 # 该应用只观测loss数值,不观测准确率,所以删去metrics选项,一会在每个epoch迭代显示时只显示loss值 checkpoint_save_path = "./checkpoint/rnn_stock.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='val_loss') history = model.fit(x_train, y_train, batch_size=64, epochs=50, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary() file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() loss = history.history['loss'] val_loss = history.history['val_loss'] plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.title('Training and Validation Loss') plt.legend() plt.show() ################## predict ###################### # 测试集输入模型进行预测 predicted_stock_price = model.predict(x_test) # 对预测数据还原---从(0,1)反归一化到原始范围 predicted_stock_price = sc.inverse_transform(predicted_stock_price) # 对真实数据还原---从(0,1)反归一化到原始范围 real_stock_price = sc.inverse_transform(test_set[60:])#索引60以后的都是真实值 # 画出真实数据和预测数据的对比曲线 plt.plot(real_stock_price, color='red', label='MaoTai Stock Price') plt.plot(predicted_stock_price, color='blue', label='Predicted MaoTai Stock Price') plt.title('MaoTai Stock Price Prediction') plt.xlabel('Time') plt.ylabel('MaoTai Stock Price') plt.legend() plt.show() ##########evaluate############## # calculate MSE 均方误差 ---> E[(预测值-真实值)^2] (预测值减真实值求平方后求均值) mse = mean_squared_error(predicted_stock_price, real_stock_price) # calculate RMSE 均方根误差--->sqrt[MSE] (对均方误差开方) rmse = math.sqrt(mean_squared_error(predicted_stock_price, real_stock_price)) # calculate MAE 平均绝对误差----->E[|预测值-真实值|](预测值减真实值求绝对值后求均值) mae = mean_absolute_error(predicted_stock_price, real_stock_price) print('均方误差: %.6f' % mse) print('均方根误差: %.6f' % rmse) print('平均绝对误差: %.6f' % mae)
LSTM
#在普通RNN代码基础上改动这两处 1.引入模块加入LSTM 2.seq模块LSTM层替换RNN层
实际代码
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dropout, Dense, LSTM import matplotlib.pyplot as plt import os import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, mean_absolute_error import math maotai = pd.read_csv('./SH600519.csv') # 读取股票文件 training_set = maotai.iloc[0:2426 - 300, 2:3].values # 前(2426-300=2126)天的开盘价作为训练集,表格从0开始计数,2:3 是提取[2:3)列,前闭后开,故提取出C列开盘价 test_set = maotai.iloc[2426 - 300:, 2:3].values # 后300天的开盘价作为测试集 # 归一化 sc = MinMaxScaler(feature_range=(0, 1)) # 定义归一化:归一化到(0,1)之间 training_set_scaled = sc.fit_transform(training_set) # 求得训练集的最大值,最小值这些训练集固有的属性,并在训练集上进行归一化 test_set = sc.transform(test_set) # 利用训练集的属性对测试集进行归一化 x_train = [] y_train = [] x_test = [] y_test = [] # 测试集:csv表格中前2426-300=2126天数据 # 利用for循环,遍历整个训练集,提取训练集中连续60天的开盘价作为输入特征x_train,第61天的数据作为标签,for循环共构建2426-300-60=2066组数据。 for i in range(60, len(training_set_scaled)): x_train.append(training_set_scaled[i - 60:i, 0]) y_train.append(training_set_scaled[i, 0]) # 对训练集进行打乱 np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 将训练集由list格式变为array格式 x_train, y_train = np.array(x_train), np.array(y_train) # 使x_train符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。 # 此处整个数据集送入,送入样本数为x_train.shape[0]即2066组数据;输入60个开盘价,预测出第61天的开盘价,循环核时间展开步数为60; 每个时间步送入的特征是某一天的开盘价,只有1个数据,故每个时间步输入特征个数为1 x_train = np.reshape(x_train, (x_train.shape[0], 60, 1)) # 测试集:csv表格中后300天数据 # 利用for循环,遍历整个测试集,提取测试集中连续60天的开盘价作为输入特征x_train,第61天的数据作为标签,for循环共构建300-60=240组数据。 for i in range(60, len(test_set)): x_test.append(test_set[i - 60:i, 0]) y_test.append(test_set[i, 0]) # 测试集变array并reshape为符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数] x_test, y_test = np.array(x_test), np.array(y_test) x_test = np.reshape(x_test, (x_test.shape[0], 60, 1)) model = tf.keras.Sequential([ LSTM(80, return_sequences=True), Dropout(0.2), LSTM(100), Dropout(0.2), Dense(1) ]) model.compile(optimizer=tf.keras.optimizers.Adam(0.001), loss='mean_squared_error') # 损失函数用均方误差 # 该应用只观测loss数值,不观测准确率,所以删去metrics选项,一会在每个epoch迭代显示时只显示loss值 checkpoint_save_path = "./checkpoint/LSTM_stock.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='val_loss') history = model.fit(x_train, y_train, batch_size=64, epochs=50, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary() file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() loss = history.history['loss'] val_loss = history.history['val_loss'] plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.title('Training and Validation Loss') plt.legend() plt.show() ################## predict ###################### # 测试集输入模型进行预测 predicted_stock_price = model.predict(x_test) # 对预测数据还原---从(0,1)反归一化到原始范围 predicted_stock_price = sc.inverse_transform(predicted_stock_price) # 对真实数据还原---从(0,1)反归一化到原始范围 real_stock_price = sc.inverse_transform(test_set[60:]) # 画出真实数据和预测数据的对比曲线 plt.plot(real_stock_price, color='red', label='MaoTai Stock Price') plt.plot(predicted_stock_price, color='blue', label='Predicted MaoTai Stock Price') plt.title('MaoTai Stock Price Prediction') plt.xlabel('Time') plt.ylabel('MaoTai Stock Price') plt.legend() plt.show() ##########evaluate############## # calculate MSE 均方误差 ---> E[(预测值-真实值)^2] (预测值减真实值求平方后求均值) mse = mean_squared_error(predicted_stock_price, real_stock_price) # calculate RMSE 均方根误差--->sqrt[MSE] (对均方误差开方) rmse = math.sqrt(mean_squared_error(predicted_stock_price, real_stock_price)) # calculate MAE 平均绝对误差----->E[|预测值-真实值|](预测值减真实值求绝对值后求均值) mae = mean_absolute_error(predicted_stock_price, real_stock_price) print('均方误差: %.6f' % mse) print('均方根误差: %.6f' % rmse) print('平均绝对误差: %.6f' % mae)
GRU
#在普通RNN代码基础上改动 1.引入模块加入GRU 2.seq模块GRU层替换RNN层
子主题
F.词嵌入
tf.keras.layers.Embedding(词汇表大小,编码维度) 编码维度就是用几个数字表示一个单词 例: tf.keras.layers.Embedding(100,3) 对1-100进行编码,其中的数字4编码为[0.25 , 0.1 , 0.11,]
x_train格式要求 [ 送入样本数,循环核时间展开步数 ]
F.LSTM
开发背景
RNN可以用过记忆体实现短期极致进行连续数据的预测, 但连续数据的序列变长时,会使展开时间步过长, 在反向传播更新参数时,梯度要按照时间步连续相乘,会导致梯度消失
计算过程与解释
解析: 如我现在在看第45页PPT 细胞态(长期记忆):旧知识(过去的44页)*遗忘门 + 新知识(现在的第45页)*输入门 记忆体(短期记忆):在我复述给别人这些内容时,调用的就是ht ht = 输出门 * tanh(长期记忆里全部PPT内容) 候选态(归纳出的新知识): tanh(Wc*[上一页PPT,当前页PPT] + bc)
F.LSTM
tf.keras.layer.LSTM(记忆体个数,return_sequences = 是否返回输出)
经验:中间层用True,最后一层用False return_sequences = True 各时间步输出ht return_sequences = False 仅最后时间步输出ht (默认)
例: model = tf.keras.Sequential([LSTM(80,return_sequences = True), Dropout(0.2), LSTM(100), Dropout(0.2), Dense(1)])
代码
LSTM
#在普通RNN代码基础上改动这两处 1.引入模块加入LSTM 2.seq模块LSTM层替换RNN层
实际代码
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dropout, Dense, LSTM import matplotlib.pyplot as plt import os import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error, mean_absolute_error import math maotai = pd.read_csv('./SH600519.csv') # 读取股票文件 training_set = maotai.iloc[0:2426 - 300, 2:3].values # 前(2426-300=2126)天的开盘价作为训练集,表格从0开始计数,2:3 是提取[2:3)列,前闭后开,故提取出C列开盘价 test_set = maotai.iloc[2426 - 300:, 2:3].values # 后300天的开盘价作为测试集 # 归一化 sc = MinMaxScaler(feature_range=(0, 1)) # 定义归一化:归一化到(0,1)之间 training_set_scaled = sc.fit_transform(training_set) # 求得训练集的最大值,最小值这些训练集固有的属性,并在训练集上进行归一化 test_set = sc.transform(test_set) # 利用训练集的属性对测试集进行归一化 x_train = [] y_train = [] x_test = [] y_test = [] # 测试集:csv表格中前2426-300=2126天数据 # 利用for循环,遍历整个训练集,提取训练集中连续60天的开盘价作为输入特征x_train,第61天的数据作为标签,for循环共构建2426-300-60=2066组数据。 for i in range(60, len(training_set_scaled)): x_train.append(training_set_scaled[i - 60:i, 0]) y_train.append(training_set_scaled[i, 0]) # 对训练集进行打乱 np.random.seed(7) np.random.shuffle(x_train) np.random.seed(7) np.random.shuffle(y_train) tf.random.set_seed(7) # 将训练集由list格式变为array格式 x_train, y_train = np.array(x_train), np.array(y_train) # 使x_train符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。 # 此处整个数据集送入,送入样本数为x_train.shape[0]即2066组数据;输入60个开盘价,预测出第61天的开盘价,循环核时间展开步数为60; 每个时间步送入的特征是某一天的开盘价,只有1个数据,故每个时间步输入特征个数为1 x_train = np.reshape(x_train, (x_train.shape[0], 60, 1)) # 测试集:csv表格中后300天数据 # 利用for循环,遍历整个测试集,提取测试集中连续60天的开盘价作为输入特征x_train,第61天的数据作为标签,for循环共构建300-60=240组数据。 for i in range(60, len(test_set)): x_test.append(test_set[i - 60:i, 0]) y_test.append(test_set[i, 0]) # 测试集变array并reshape为符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数] x_test, y_test = np.array(x_test), np.array(y_test) x_test = np.reshape(x_test, (x_test.shape[0], 60, 1)) model = tf.keras.Sequential([ LSTM(80, return_sequences=True), Dropout(0.2), LSTM(100), Dropout(0.2), Dense(1) ]) model.compile(optimizer=tf.keras.optimizers.Adam(0.001), loss='mean_squared_error') # 损失函数用均方误差 # 该应用只观测loss数值,不观测准确率,所以删去metrics选项,一会在每个epoch迭代显示时只显示loss值 checkpoint_save_path = "./checkpoint/LSTM_stock.ckpt" if os.path.exists(checkpoint_save_path + '.index'): print('-------------load the model-----------------') model.load_weights(checkpoint_save_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path, save_weights_only=True, save_best_only=True, monitor='val_loss') history = model.fit(x_train, y_train, batch_size=64, epochs=50, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) model.summary() file = open('./weights.txt', 'w') # 参数提取 for v in model.trainable_variables: file.write(str(v.name) + '\n') file.write(str(v.shape) + '\n') file.write(str(v.numpy()) + '\n') file.close() loss = history.history['loss'] val_loss = history.history['val_loss'] plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.title('Training and Validation Loss') plt.legend() plt.show() ################## predict ###################### # 测试集输入模型进行预测 predicted_stock_price = model.predict(x_test) # 对预测数据还原---从(0,1)反归一化到原始范围 predicted_stock_price = sc.inverse_transform(predicted_stock_price) # 对真实数据还原---从(0,1)反归一化到原始范围 real_stock_price = sc.inverse_transform(test_set[60:]) # 画出真实数据和预测数据的对比曲线 plt.plot(real_stock_price, color='red', label='MaoTai Stock Price') plt.plot(predicted_stock_price, color='blue', label='Predicted MaoTai Stock Price') plt.title('MaoTai Stock Price Prediction') plt.xlabel('Time') plt.ylabel('MaoTai Stock Price') plt.legend() plt.show() ##########evaluate############## # calculate MSE 均方误差 ---> E[(预测值-真实值)^2] (预测值减真实值求平方后求均值) mse = mean_squared_error(predicted_stock_price, real_stock_price) # calculate RMSE 均方根误差--->sqrt[MSE] (对均方误差开方) rmse = math.sqrt(mean_squared_error(predicted_stock_price, real_stock_price)) # calculate MAE 平均绝对误差----->E[|预测值-真实值|](预测值减真实值求绝对值后求均值) mae = mean_absolute_error(predicted_stock_price, real_stock_price) print('均方误差: %.6f' % mse) print('均方根误差: %.6f' % rmse) print('平均绝对误差: %.6f' % mae)
F.GRU
简介
介绍:简化后的LSTM 特点:使记忆体ht融合了长期记忆和短期记忆
计算过程
 更新门:取值范围[0-1] 重置门:取值范围[0-1] 记忆体:ht = 多大程度不更新 * 上一页PPT + 多大程度更新 * 这一页PPT 候选隐藏层: 新知识 = tanh(W * [ 重置度 * 上一页PPT,当前输入 ])
F.GRU
tf.keras.layers.GRU(记忆体个数 , return_sequences = 是否返回输出)
经验:一般中间层True 最后一层False return_sequences = True 各时间步输出ht return_sequences = False 仅最后时间步输出ht(默认)
例: model = tf.keras.Sequential([GRU(80,return_sequences=True), Dropout(0.2), GRU(100), Dropout(0.2), Dense(1) ])
代码
GRU
#在普通RNN代码基础上改动 1.引入模块加入GRU 2.seq模块GRU层替换RNN层
子主题
快速生成独热码代码

re正则库
函数
findall( )
search( )
match( )
>>> m =re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") >>> m.group(0) # The entire match 'Isaac Newton' >>> m.group(1) # The first parenthesized subgroup. 'Isaac' >>> m.group(2) # The second parenthesized subgroup. 'Newton' >>> m.group(1, 2) # Multiple arguments give us a tuple. ('Isaac', 'Newton')
split( )
>>> re.split(r'\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] >>> re.split(r'(\W+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split(r'\W+', 'Words, words, words.', 1) ['Words', 'words, words.'] >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE) ['0', '3', '9']
>>> re.split(r'(\W+)', '...words, words...') ['', '...', 'words', ', ', 'words', '...', '']
>>> re.split(r'\b', 'Words, words, words.') ['', 'Words', ', ', 'words', ', ', 'words', '.'] >>> re.split(r'\W*', '...words...') ['', '', 'w', 'o', 'r', 'd', 's', '', ''] >>> re.split(r'(\W*)', '...words...') ['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
sub( )
subn( )
基础知识
元字符
\W 取反,匹配非单词字符
匹配中间的空格符
重复限定符
分组
字符 功能 | 匹配左右任意一个表达式 (ab) 将括号中字符作为一个分组 \num 引用分组num匹配到的字符串 (?P<name>) 分组起别名 (?P=name) 引用别名为name分组匹配到的字符串
子主题
转义
条件或
^:匹配字符串开始 ():条件或 \d : 匹配数字 {8}:重复8次 $ :匹配字符串结尾
可以匹配多个相同字符特征
区间
边界
字符 功能 ^ 匹配字符串开头 $ 匹配字符串结尾 \b 匹配一个单词的边界 \B 匹配非单词边界
#定义规则匹配str="ho ve r" #1. 以字母开始 ^\w #2. 中间有空字符 \s #3. \b的两种解释是: #'\b', 如果前面不加r, 那么解释器认为是转义字符“退格键backspace”; #r'\b', 如果前面加r, 那么解释器不会进行转义,\b 解释为正则表达式模式中的字符串边界。 #4. ve两边分别限定匹配单词边界 >>> import re >>> str ="dasdho ve rgsdf" >>> pattern =r"^\w+\s\bve\b\sr" #加r表示边界,^\w+表示开头有1个或多个字母。\s空格 \b 边界以此类推 >>> result =re.match(pattern, str) >>> result.group() 'dasdho ve r'
方括号
#首先清楚手机号的规则 #1.都是数字 2.长度为11 3.第一位是1 4.第二位是35678中的一位 >>> import re >>> pattern ="1[35678]\d{9}" >>> phoneStr ="18230092223" >>> result =re.match(pattern,phoneStr) >>> result.group() '18230092223'
进阶知识
零宽断言
定义
断言:正则可以指明在指定的内容前面或后边会出现满足指定规则的内容 零宽:没有宽度, 在正则中,断言只匹配位置,不占字符,也就是说,匹配结果里 是不会返回断言本身
正向先行断言(正前瞻)
语法:(? = pattern) 作用: 匹配pattern 表达式的前面内容,不返回本身
例:匹配文章阅读数 假设我们要用爬虫抓取csdn里的文章阅读量。通过查看源代码可以看到文章阅读量这个内容是这样的结构
表示我知道在这个字符前是多个数字,你给我找找
正向后行断言(正后顾)
语法:(?<=pattern) 作用:匹配pattern表达式的后边的内容,不返回本身
()=pattern 是参照字符 表示在 阅读数:后边有几个数字 你都给我找来
负向先行断言(负前瞻)
语法:(?!pattern) 作用:匹配非pattern表达式的前边内容,不返回本身
例
#(?<=abc)def ,并不是从 a 开始搜索,而是从 d 往回看的。你可能更加愿意使用 search() 函数,而不是 match() 函数: >>> import re >>> m =re.search('(?<=abc)def', 'abcdef') >>> m.group(0) 'def' #搜索一个跟随在连字符后的单词 >>> m =re.search(r'(?<=-)\w+', 'spam-egg') >>> m.group(0) 'egg'
捕获和非捕获
数字编号捕获组
命名编号捕获组
>>> m =re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.group('first_name') 'Malcolm' >>> m.group('last_name') 'Reynolds' #命名组合同样可以通过索引值引用 >>> m.group(1) 'Malcolm' >>> m.group(2) 'Reynolds'
非捕获组
反向引用
子主题
贪婪
定义
例
在第一串数字中,只需要返回617就可以了, 但是它贪婪的匹配到了最大能匹配的字符,即617628
一个量词如此贪婪,多个量词凑一起,如何支配自己的匹配权? 答:如果字符串能满足它们最大程度的匹配,就互不干扰 如果不能满足,根据深度优先原则,也就是从左到右的每一个贪婪量词, 优先最大数量的满足,剩余再分配下一个量词匹配
优先满足前边的
与懒惰对比
从字母i开始到o结束找最大长度的字符 下图为贪婪
懒惰会少个o
懒惰
语法
前边能少匹配就少匹配,后边能多匹配就多匹配 
反义
就是不想 匹配某些字符
非数字的匹配
非数字,字母,下划线,汉字
非空字符
不是l的字符
例
单个字符匹配
1.写出字符本身
需求:匹配l 解决:写l
2.通配符
. 代表任意字符 故能匹配到所有字符
3.方括号匹配
[ ]里边是“或”的关系 即有里边任意字符都会被匹配
反方括号匹配 就不匹配方括号里的 [^d] 可以看到只有d没有匹配到
匹配所有大小写字符
[a-z]
[A-Z]
匹配所有数字
[0-9]
综合使用
[a-zA-Z0-9] #除了空格都被匹配到了
高效工具
\w 匹配所有单词字符
\d 匹配所有数字
条件匹配
#匹配出0-100之间的数字 #首先:正则是从左往又开始匹配 #经过分析: 可以将0-100分为三部分 #1. 0 "0$" #2. 100 "100$" #3. 1-99 "[1-9]\d{0,1}$" #所以整合如下 >>> import re >>> pattern =r"0$|100$|[1-9]\d{0,1}$" >>> result = re.match(pattern,"27") >>> result.group() '27' >>> result =re.match(pattern,"212") >>> result.group() Traceback (most recent call last): File "<stdin>", line 1, in<module> AttributeError: 'NoneType'object has no attribute 'group' #将0考虑到1-99上,上述pattern还可以简写为:pattern=r"100$|[1-9]?\d{0,1}$"
工具网站
正则表达式教程 大纲:https://gist.github.com/JavaCS3/e36e494e78a02049950bfa7c7ebeb929 工具:https://regex101.com
自动生成的代码
文章
https://blog.csdn.net/yunweimao/article/details/106688046?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163585413416780271535208%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=163585413416780271535208&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-106688046.pc_search_mgc_flag&utm_term=re%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F&spm=1018.2226.3001.4187
string库
函数
头文件:#include<string.h>
找特定字符
函数:char * strstr()
倒腾文件
shutil
原文链接:https://blog.csdn.net/weixin_41261833/article/details/108050152
Pyuserinput
安装
pip install pymouse
鼠标命令
鼠标控制click 左右键参数叫button
键盘命令
import pykeyboard --引用 k = pykeyboard.PyKeyboard( ) --实例化 k.type_string('abcdefg') --输入内容 k.press_key('a') --按a键 k.release_key('a') --松开a键 k.tap_key('a') --点击a键 k.tap_key('a', n=2, interval=5) --点击a键2次,每次间隔5秒 k.tap_key(k.function_keys[5]) --功能键F5 k.press_keys([k.alt_key, 'a']) --组合按键,试验不成功
OS
创建目录
创建多层目录
os.makedirs(name,mode=0o777,exist_ok=False)
什么叫多层
sklearn
文档地址:https://scikit-learn.org/
准确率metrics
sklearn.metrics.accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None)[source]
normalize=False时返回预测正确个数
注意
不支持一个batch的iter进去 如Y_hat是[bs128,seq_len150] Y_true也是[bs128,seq_len150] 但可以分批计算,但分批不如最后一行省事