假期修习之旅:技能栈的拓展
数据分析学习
学习视频:https://www.bilibili.com/video/BV1hx411d7jb?p=1
学习资料:
- 链接:https://pan.baidu.com/s/1imOJ5LituooRaPeLg_eWyA 提取码:5qe2
- https://matplotlib.org/
- https://www.runoob.com/numpy/numpy-matplotlib.html
matplotlib:设置图片的大小+保存
from matplotlib import pyplot as plt \'\'\' --> figure图形图标的意思,在这里指的就是我们画的图 -->通过实例化一个figure并且传递参数,能够在后台自动使用该figure实例 -->在图像模糊的时候可以传入dpi参数(每英寸点的个数),让图片更加清晰 \'\'\' x= range(2,26,2) y = [15,13,14.5,17,20,25,26,26,27,22,18,15] # 设置图片大小 plt.figure(figsize=(20,8),dpi=80) plt.plot(x,y) #保存图片 plt.savefig("./t1.png") #显示图片 plt.show()
matplotlib:坐标刻度显示
\'\'\' @Time : 2021/1/5 11:22 @Author : laolao @FileName: matplotlib_day1.py \'\'\' import random from matplotlib import pyplot as plt \'\'\' --> figure图形图标的意思,在这里指的就是我们画的图 -->通过实例化一个figure并且传递参数,能够在后台自动使用该figure实例 -->在图像模糊的时候可以传入dpi参数(每英寸点的个数),让图片更加清晰 \'\'\' x = range(2, 26, 2) y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15] # 设置图片大小 plt.figure(figsize=(20, 8), dpi=80) # 绘图 plt.plot(x, y) # 设置x轴的刻度 设置y轴刻度 # 法一 # plt.xticks(range(2,26)) # 法二 _xtick_labels = [i / 2 for i in range(4, 49)] plt.xticks(_xtick_labels) plt.yticks(range(min(y), max(y) + 1)) # 保存图片 plt.savefig("./t1.png") # 显示图片 plt.show()
matplotlib:坐标的中文和格式化显示
如果列表a表示10点到12点的每一分钟的气温如何绘制折线图观察每分钟气温的变化情况?
""" @Time : 2021/1/5 11:22 @Author : laolao @FileName: matplotlib_day1.py """ import random from matplotlib import pyplot as plt import matplotlib # 设置中文 法一 font = {\'family\': \'MicroSoft YaHei\', \'weight\': \'bold\', \'size\': 12} matplotlib.rc("font",**font) # **font将字典拆包,以关键字输入 # 设置中文 法二 matplotlib.rc("font",family="MicroSoft YaHei",weight="bold") x = range(120) y = [random.randint(20, 35) for i in range(120)] plt.plot(x, y) # 调整x轴的刻度,格式化输出(保证两个列表的一一对应) # _x = list(x)[::10] # _xtick_lables = ["hello,{}".format(i) for i in _x] _x = list(x) _xtick_lables = ["10点{}分".format(i) for i in range(60)] _xtick_lables += ["11点{}分".format(i - 60) for i in range(60, 120)] # 取步长 plt.xticks(_x[::3], _xtick_lables[::3], rotation=45) # rotation 旋转的度数 plt.show()
手动引用电脑上的字体
""" @Time : 2021/1/5 11:22 @Author : laolao @FileName: matplotlib_day1.py """ import random from matplotlib import pyplot as plt, font_manager import matplotlib my_font = font_manager.FontProperties(fname="C:\\Users\坂田银时\AppData\Local\Microsoft\Windows\Fonts\禹卫书法云墨简体.ttf") x = range(120) y = [random.randint(20, 35) for i in range(120)] plt.plot(x, y) # 调整x轴的刻度,格式化输出(保证两个列表的一一对应) # _x = list(x)[::10] # _xtick_lables = ["hello,{}".format(i) for i in _x] _x = list(x) _xtick_lables = ["10点{}分".format(i) for i in range(60)] _xtick_lables += ["11点{}分".format(i - 60) for i in range(60, 120)] # 取步长 plt.xticks(_x[::3], _xtick_lables[::3], rotation=45,fontproperties=my_font) # rotation 旋转的度数 plt.show()
matplotlib:添加描述信息
""" @Time : 2021/1/5 11:22 @Author : laolao @FileName: matplotlib_day1.py """ import random from matplotlib import pyplot as plt, font_manager import matplotlib my_font = font_manager.FontProperties(fname="C:\\Users\坂田银时\AppData\Local\Microsoft\Windows\Fonts\禹卫书法云墨简体.ttf",size=16) x = range(120) y = [random.randint(20, 35) for i in range(120)] plt.plot(x, y) _x = list(x) _xtick_lables = ["10点{}分".format(i) for i in range(60)] _xtick_lables += ["11点{}分".format(i - 60) for i in range(60, 120)] plt.xticks(_x[::3], _xtick_lables[::3], rotation=45,fontproperties=my_font) # rotation 旋转的度数 # 添加描述信息 plt.xlabel("时间",fontproperties=my_font) plt.ylabel("温度 单位℃",fontproperties=my_font) plt.title("10点到12点每分钟的气温变化情况",fontproperties=my_font) plt.show()
matplotlib:添加网格
假设大家在30岁的时候,根据自己的实际情况,统计出来了从11岁到30岁每年交的女(男)朋友的数量如列表a,请绘制出该数据的折线图,以便分析自己每年交女(男)朋友的数量走势
a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
要求:
y轴表示个数
x轴表示岁数,比如11岁,12岁等
""" @Time : 2021/1/5 11:22 @Author : laolao @FileName: matplotlib_day1.py """ import random from matplotlib import pyplot as plt, font_manager my_font = font_manager.FontProperties(fname="C:\\Users\坂田银时\AppData\Local\Microsoft\Windows\Fonts\禹卫书法云墨简体.ttf",size=16) x = range(11,31) a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1] plt.plot(x, a) _x = list(x) _xtick_lables = ["{}岁".format(i) for i in range(11,31)] plt.xticks(_x, _xtick_lables, rotation=45,fontproperties=my_font) # rotation 旋转的度数 plt.yticks(range(0,9)) # 绘制网格 plt.grid(alpha=0.5) # alpha 设置透明度 # 添加描述信息 plt.xlabel("年龄",fontproperties=my_font) plt.ylabel("男朋友的个数 单位(个)",fontproperties=my_font) plt.title("11到30岁交往的男朋友的个数",fontproperties=my_font) plt.show()
matplotlib:同时绘制两个曲线+设置图例+线条自定义
假设大家在30岁的时候,根据自己的实际情况,统计出来了你和你同桌各自从11岁到30岁每年交的女(男)朋友的数量如列表a和b,请在一个图中绘制出该数据的折线图,以便比较自己和同桌20年间的差异,同时分析每年交女(男)朋友的数量走势
a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
b = [1,0,3,1,2,2,3,3,2,1 ,2,1,1,1,1,1,1,1,1,1]
要求:
y轴表示个数
x轴表示岁数,比如11岁,12岁等
""" @Time : 2021/1/5 11:22 @Author : laolao @FileName: matplotlib_day1.py """ import random from matplotlib import pyplot as plt, font_manager my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simkai.ttf",size=16) x = range(11,31) a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1] b = [1,0,3,1,2,2,3,3,2,1 ,2,1,1,1,1,1,1,1,1,1] # 线条自定义 # linestyle=设置线条的风格 # linewidth=设置线条粗线 # color=设置绘图演示 plt.plot(x, a,label="自己",color="cyan",linestyle=":",linewidth=5) plt.plot(x,b,label="同桌",color="orange",linestyle="-.") _x = list(x) _xtick_lables = ["{}岁".format(i) for i in range(11,31)] plt.xticks(_x, _xtick_lables, rotation=45,fontproperties=my_font) plt.yticks(range(0,9)) # 绘制网格 plt.grid(alpha=0.5) # alpha 设置透明度 plt.xlabel("年龄",fontproperties=my_font) plt.ylabel("男朋友的个数 单位(个)",fontproperties=my_font) plt.title("11到30岁交往的男朋友的个数",fontproperties=my_font) # 添加图例 # prop=设置字体以方便中文显示 # loc=设置图例所在位置 plt.legend(prop=my_font,loc="upper left") plt.show()
matplotlib:第一阶段总结
matplotlib:绘制散点图
假设通过爬虫你获取到了北京2016年3,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温和随时间(天)变化的某种规律?
a = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
b = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]
from matplotlib import pyplot as plt, font_manager y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23] y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6] x_3 = range(1,32) x_10 = range(51,82) plt.figure(figsize=(20,8),dpi=80) # 绘制散点图 plt.scatter(x_3,y_3,label="3月份") plt.scatter(x_10,y_10,label="10月份") _x = list(x_3)[::3]+list(x_10)[::3] _xtick_labels = ["3月{}日".format(i) for i in x_3] _xtick_labels +=["10月{}日".format(i-50) for i in x_10] my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simkai.ttf",size=16) plt.xticks(_x,_xtick_labels,fontproperties=my_font,rotation=45) plt.legend(loc="upper left",prop=my_font) plt.xlabel("时间",fontproperties=my_font) plt.ylabel("温度",fontproperties=my_font) plt.show()
matplotlib:绘制条形图
假设你获取到了2017年内地电影票房前20的电影(列表a)和电影票房数据(列表b),那么如何更加直观的展示该数据?
a = [“战狼2″,”速度与激情8″,”功夫瑜伽”,”西游伏妖篇”,”变形金刚5:最后的骑士”,”摔跤吧!爸爸”,”加勒比海盗5:死无对证”,”金刚:骷髅岛”,”极限特工:终极回归”,”生化危机6:终章”,”乘风破浪”,”神偷奶爸3″,”智取威虎山”,”大闹天竺”,”金刚狼3:殊死一战”,”蜘蛛侠:英雄归来”,”悟空传”,”银河护卫队2″,”情圣”,”新木乃伊”,]
b=[56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23] 单位:亿
from matplotlib import pyplot as plt, font_manager a = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5:最后的骑士", "摔跤吧!爸爸", "加勒比海盗5:死无对证", "金刚:骷髅岛", "极限特工:终极回归", "生化危机6:终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3:殊死一战", "蜘蛛侠:英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊", ] b = [56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61, 11.28, 11.12, 10.49, 10.3, 8.75, 7.55, 7.32, 6.99, 6.88, 6.86, 6.58, 6.23] plt.figure(figsize=(20, 15), dpi=80) # 绘制条形图 plt.bar(a,b,width=0.3) my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simkai.ttf", size=16) plt.xticks(a,fontproperties=my_font,rotation=90) plt.show()
横着的条形图
from matplotlib import pyplot as plt,font_manager a = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5:最后的骑士", "摔跤吧!爸爸", "加勒比海盗5:死无对证", "金刚:骷髅岛", "极限特工:终极回归", "生化危机6:终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3:殊死一战", "蜘蛛侠:英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊", ] b = [56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61, 11.28, 11.12, 10.49, 10.3, 8.75, 7.55, 7.32, 6.99, 6.88, 6.86, 6.58, 6.23] plt.figure(figsize=(20, 8), dpi=80) # 绘制横着的条形图 plt.barh(a,b,height=0.3,color="orange") my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simkai.ttf", size=16) plt.yticks(a,fontproperties=my_font) plt.grid(alpha=0.3) plt.show()
matplotlib:同时绘制多个条形图
假设你知道了列表a中电影分别在2017-09-14(b_14), 2017-09-15(b_15), 2017-09-16(b_16)三天的票房,为了展示列表中电影本身的票房以及同其他电影的数据对比情况,应该如何更加直观的呈现该数据?
a = [“猩球崛起3:终极之战”,”敦刻尔克”,”蜘蛛侠:英雄归来”,”战狼2″]
b_16 = [15746,312,4497,319]
b_15 = [12357,156,2045,168]
b_14 = [2358,399,2358,362]
from matplotlib import pyplot as plt, font_manager a = ["猩球崛起3:终极之战", "敦刻尔克", "蜘蛛侠:英雄归来", "战狼2"] b_16 = [15746, 312, 4497, 319] b_15 = [12357, 156, 2045, 168] b_14 = [2358, 399, 2358, 362] plt.figure(figsize=(20, 8), dpi=80) # 绘制多个条形图 bar_width = 0.2 # 设置柱子的粗细 x_14 = list(range(len(a))) x_15 = [i + bar_width for i in x_14] x_16 = [i + bar_width * 2 for i in x_14] plt.bar(range(len(a)), b_14, width=bar_width, label="9月14日") plt.bar(x_15, b_15, width=bar_width, label="9月15日") plt.bar(x_16, b_16, width=bar_width, label="9月16日") my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simkai.ttf", size=16) # 设置图例 plt.legend(prop=my_font) plt.xticks(x_15, a, fontproperties=my_font) plt.grid(alpha=0.3) plt.show()
matplotlib:绘制直方图
假设你获取了250部电影的时长(列表a中),希望统计出这些电影时长的分布状态(比如时长为100分钟到120分钟电影的数量,出现的频率)等信息,你应该如何呈现这些数据?
a=[131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]
from matplotlib import pyplot as plt, font_manager a=[131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150] my_font = font_manager.FontProperties(fname="C:\Windows\Fonts\simkai.ttf", size=16) plt.figure(figsize=(20, 8), dpi=80) #计算组数 d = 3 num_bins = int((max(a)-min(a))/d) # 绘制频数直方图 plt.hist(a,num_bins,density=False) #density = True 显示频率 # 设置x轴的刻度 plt.xticks(range(min(a),max(a)+d,d)) plt.grid(alpha=0.3) plt.show()
matplotlib:绘制直方图
在美国2004年人口普查发现有124 million的人在离家相对较远的地方工作。根据他们从家到上班地点所需要的时间,通过抽样统计(最后一列)出了下表的数据,这些数据能够绘制成直方图么?
interval = [0,5,10,15,20,25,30,35,40,45,60,90]
width = [5,5,5,5,5,5,5,5,5,15,30,60]
quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,47]
from matplotlib import pyplot as plt, font_manager interval = [0,5,10,15,20,25,30,35,40,45,60,90] width = [5,5,5,5,5,5,5,5,5,15,30,60] quantity = [836,2737,3723,3926,3596,1438,3273,642,824,613,215,47] plt.figure(figsize=(20,8),dpi=80) plt.bar(range(len(quantity)),quantity,width=1) _x = [i-0.5 for i in range(13)] _xtick_labels = interval+[150] plt.xticks(_x,_xtick_labels) plt.grid(alpha=0.3) plt.show()
拓展学习
https://echarts.apache.org/zh/index.html
https://plotly.com/python/
http://seaborn.pydata.org/
numpy:基本使用
import random import numpy as np # numpy 生成数组的三种形式 t1 = np.array([1,2,3,]) t2 = np.array(range(10)) t3 = np.arange(20) print(t1,t2,t3) # 查看数组类型 print(type(t3)) # 查看数组中数据的类型 print(t3.dtype) # 自定义数组数据类型 t4 = np.array(range(1,4),dtype=float) print(t4) print(t4.dtype) # 调整数据类型 t6 = t4.astype("int8") print(t6.dtype) # 小数数组 t7 = np.array([random.random() for i in range(10)]) print(t7) print(t7.dtype) # 四舍五入保留两位 t8 = np.round(t7,2) print(t8) print(t8.dtype)
numpy:数组形状
import numpy as np a = np.array([[3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9]]) print(a) print(a.shape) b = np.array([ [[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]] ]) print(b) print(b.shape) print("*" * 50) # 更改数组的行列值 t4 = np.arange(12) print(t4.reshape((3, 4))) # 三行四列 print(t4.reshape((2, 3, 2))) # 两块数据,3*2的 # 转换为一维的 print("*" * 50) print(a.reshape((a.shape[0] * a.shape[1],))) # 方法一 print(a.flatten()) # 方法二
numpy:数组加减乘除
import numpy as np a = np.array([[3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9]]) # 广阔机制 print(a + 1) print(a * 2) print(a / 3) # 两个矩阵相加--》对应的值相加 print("*" * 50) b = np.arange(100, 112).reshape(2, 6) print(a + b) # 矩阵相减:二维与一维,有一个维度一样就可以,三维与二维需要两个维度一样 c = np.arange(0, 6) print(a - c) # a中的每一行减去c d = np.arange(3, 5).reshape(2, 1) print(a - d) # a中的每一列减去d
numpy:读取csv+转置
import numpy as np # 读取csv文件 a_path = "快速查询.csv" b_path = "" ### delimiter指定用什么分割 ### detype指定数据类型 t1 = np.loadtxt(a_path, delimiter=",", dtype="int") # 求矩阵的转置 print(t1) print("*" * 100) ## 法一 print(t1.T) ## 法二 print(t1.transpose()) ## 法三 print(t1.swapaxes(1, 0)) # 输入0轴和1轴 # 法四 t2 = np.loadtxt(a_path, delimiter=",", dtype="int", unpack=True) print(t2)
numpy:数据筛选-索引+数据切片
import numpy as np a_path = "快速查询.csv" t1 = np.loadtxt(fname=a_path, delimiter=",", dtype="int") # 取矩阵中的某一行 print(t1[2]) # 取连续的多行 print(t1[2:4]) # 取不连续的多行 print(t1[[2, 4, 7]]) # 取列 print(t1[:, 0]) print(t1[:, 2:]) print(t1[:, [0, 2]]) # 取多列多行 3-5行的1,3列 print(t1[2:5, [0, 2]]) # 取多个不相领的点:第一行为行号,第二行为列号,竖着看 print(t1[[0, 2], [0, 1]])
numpy:数据筛选-高级应用
布尔索引-数值修改+筛选
import numpy as np a_path = "快速查询.csv" t1 = np.loadtxt(fname=a_path, delimiter=",", dtype="int") # 数值的条件修改:将矩阵中小于10的修改为3 print(t1 < 10) t1[t1 < 10] = 3 print(t1) # 数值的筛选 print(t1[t1>10000])
where ,clip筛选
import numpy as np a_path = "快速查询.csv" t1 = np.loadtxt(fname=a_path, delimiter=",", dtype="int") # 三元运算:将矩阵中小于100的修改为200并且大于100的为300 print(np.where(t1 <= 100, 200, 300)) # 小于100的替换为100,大于5000的替换为5000 print(t1.clip(100,5000))
numpy:nan+常用的统计方法
import numpy as np def demo(): a_path = "快速查询.csv" t1 = np.loadtxt(fname=a_path, delimiter=",", dtype="int") # 将(3,3)位置的值赋值为nan print(t1) t2 = t1.astype(float) t2[3, 3] = np.nan print(t2) # 统计数组中不为0的个数(nan不算) print(np.count_nonzero(t2)) # 统计数组中nan的个数 print(np.count_nonzero(t2 != t2)) print(np.count_nonzero(np.isnan(t2))) # nan与任何值计算都为nan print(t2.sum()) t3 = np.arange(12).reshape(3, 4) print(t3) print(np.sum(t3)) # 按照列压缩 print(np.sum(t3, axis=0)) # 按照行压缩 print(np.sum(t3, axis=1)) # 计算中值 print(t2.mean(axis=0)) # 计算最大最小值 print(t2.min(axis=1)) print(t2.max(axis=1)) # 计算极值(最大最小之差) print(t2.ptp(axis=1)) def fill_ndarry(t4): \'\'\' 在有nan的数组中求均值,需要将nan替换为标准差 :param t4: :return: \'\'\' for i in range(t4.shape[1]): temp_col = t4[:, i] # 当前的一列 nan_num = np.count_nonzero(np.isnan(temp_col)) if nan_num != 0: temp_not_nan_col = temp_col[temp_col == temp_col] # 当前一列不为nan的arry temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean() # 将值为nan的赋值为均值 return t4 if __name__ == \'__main__\': # 计算标准差 t4 = np.arange(12).reshape((3, 4)).astype("float") print(np.std(t4)) # 计算带有nan的平均值 t4[1, 2:] = np.nan # 第2行,2-last列的数据 print(t4) print(fill_ndarry(t4))
numpy:总结
英国和美国各自youtube1000的数据结合之前的matplotlib绘制出各自的评论数量的直方图
import numpy as np from matplotlib import pyplot as plt us_file_path = "./youtube_video_data/US_video_data_numbers.csv" uk_file_path = "./youtube_video_data/GB_video_data_numbers.csv" t_us = np.loadtxt(fname=us_file_path, delimiter=",", dtype="int") t_us_comments = t_us[:,-1] t_us_comments = t_us_comments[t_us_comments<=5000] d = 50 bin_nums =(t_us_comments.max()-t_us_comments.min())//d # 绘图 plt.figure(figsize=(20,8),dpi=80) plt.hist(t_us_comments,bin_nums) plt.grid(alpha=0.4) plt.show()
希望了解英国的youtube中视频的评论数和喜欢数的关系,应该如何绘制改图
import numpy as np from matplotlib import pyplot as plt us_file_path = "./youtube_video_data/US_video_data_numbers.csv" uk_file_path = "./youtube_video_data/GB_video_data_numbers.csv" t_uk = np.loadtxt(fname=uk_file_path, delimiter=",", dtype="int") # 选择喜欢数比2w小的数据 t_uk = t_uk[t_uk[:,1]<=20000] t_uk_comments = t_uk[:,-1] t_uk_like = t_uk[:,1] # 绘图 plt.figure(figsize=(20,8),dpi=80) plt.scatter(t_uk_like,t_uk_comments) plt.grid(alpha=0.4) plt.show()
numpy:数据拼接
# encoding:utf-8 import numpy as np def 竖直拼接(t1, t2): print(np.vstack((t1, t2))) def 水平拼接(t1, t2): print(np.hstack((t1, t2))) def 行交换(t1): print(t1) t1[[1, 2], :] = t1[[2, 1], :] print(t1) def 列交换(t2): print(t2) t2[:, [0, 2]] = t2[:, [2, 0]] print(t2) if __name__ == \'__main__\': t1 = np.arange(12).reshape(3, 4) t2 = np.arange(12, 24).reshape(3,4) # 竖直拼接(t1,t2) 列交换(t1)
panda:Series基本使用
import pandas as pd def 基本使用(): t = pd.Series([1, 2, 34, 435, 5]) print(t) def 修改类型(): t = pd.Series([1, 2, 34, 435, 5]) print(t.astype("float")) def 跟换索引(): t = pd.Series([1, 2, 34, 435, 5], index=list("abcde")) print(t) def 通过字典创建(tamp): print(pd.Series(tamp)) def 索引(temp): a = pd.Series(temp) # print(a[\'Set-Cookie\']) # print(a[1]) # print(a[:2]) print(a[[1, 2]]) def 获取索引值(temp): a = pd.Series(temp) print(a.index) def 获取键值(temp): a = pd.Series(temp) print(a.values) if __name__ == \'__main__\': tamp = { \'Set-Cookie\': \'delPer=0; path=/; domain=.baidu.com\', \'Set-Cookie1\': \'BD_CK_SAM=1;path=/\', \'Set-Cookie2\': \'PSINO=5; domain=.baidu.com; path=/\', \'Set-Cookie3\': \'BDSVRTM=27; path=/\' } # 跟换索引() # 通过字典创建() # 修改类型() # 索引(temp=tamp) # 获取索引值(temp=tamp) 获取键值(temp=tamp)
panda:DataFrame基本使用
import pandas as pd import numpy as np def 读取CSV(): t = pd.read_csv("快速查询.csv") print(t) def DataFrame类型(): print(pd.DataFrame(np.arange(12).reshape(3, 4))) def 自定义索引(): print(pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("wxyz"))) def 字典赋值(): tamp = { \'Set-Cookie\': [\'delPer=0; path=/; domain=.baidu.com\'], \'Set-Cookie1\': [\'BD_CK_SAM=1;path=/\'], \'Set-Cookie2\': [\'PSINO=5; domain=.baidu.com; path=/\'], \'Set-Cookie3\': [\'BDSVRTM=27; path=/\'] } print(pd.DataFrame(tamp)) def 列表赋值(): a = [{"name": "123", "age": 32, "tel": 1000}, {"name": "345", "age": 12, "tel": 46544}, {"name": "564", "age": 23, } ] print(pd.DataFrame(a)) def 基本函数(): a = [{"name": "123", "age": 32, "tel": 1000}, {"name": "345", "age": 12, "tel": 46544}, {"name": "564", "age": 23, } ] b = pd.DataFrame(a) print(b.dtypes, end="\n\n") print(b.shape, end="\n\n") print(b.values, end="\n\n") print(b.ndim, end="\n\n") # 显示数据维度 print(b.head(2), end="\n\n") # 显示前5行 print(b.tail(2), end="\n\n") print(b.info(), end="\n\n") print(b.describe(), end="\n\n") # 个数,平均值,方差,最小值,分位数,最大值 if __name__ == \'__main__\': # DataFrame类型() # 字典赋值(tamp) # 列表赋值() # 基本函数() 排序方法()
panda:DataFrame索引
import pandas as pd import numpy as np def 排序方法(): \'\'\' 方括号 写数字,表示取行,对行进行操作 写字符串,表示取索引,对列进行操作 :return: \'\'\' df = pd.read_csv("快速查询.csv") # ascending=False降序排序 df = df.sort_values(by="本月", ascending=False) print(df[:20]) print(df[:20]["本月"]) # 取前20行的“本月”列的数据 def loc方法(): \'\'\' 标签索引 :return: \'\'\' t = pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("wxyz")) print(t, end="\n\n") print(t.loc[\'a\', \'z\'], end="\n\n") print(t.loc[\'a\'], end="\n\n") print(t.loc[:, \'y\'], end="\n\n") def iloc方法(): """ 位置索引 :return: """ t = pd.DataFrame(np.arange(12).reshape(3, 4)) print(t, end="\n\n") print(t.iloc[1, :], end="\n\n") print(t.iloc[:, 2], end="\n\n") print(t.iloc[:, [2, 1]], end="\n\n") print(t.iloc[[0, 2], [2, 1]], end="\n\n") t.iloc[1:,:2] = 30 print(t, end="\n\n") if __name__ == \'__main__\': # 排序方法() # loc方法() iloc方法()
panda:缺失数据处理
import pandas as pd import numpy as np def 索引(): df = pd.read_csv("快速查询.csv") df = df.sort_values(by="本月", ascending=False) print(df[(800 < df["本月"]) & (df["本月"] < 1000)]) def 缺失数据处理(): df = pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("wxyz")) df.loc["c":, "x":] = np.nan # print(df, end="\n\n") # print(pd.notnull(df), end="\n\n") # print(pd.isnull(df), end="\n\n") # print(df[pd.notnull(df["z"])],end="\n\n") # 选择w这一列中不为non的所在行 # print(df.dropna(axis=0,how="all"), end="\n\n") # 当前的数据全部为nan的时候才删掉 # print(df.dropna(axis=0, how="any",inplace=True), end="\n\n") # 原地修改 print(df, end="\n\n") # print(df.fillna(df.mean())) # 用均值填充nan的值 print(df[\'x\'].fillna(df[\'x\'].mean())) # 只对某一列进行填充 if __name__ == \'__main__\': # 索引() 缺失数据处理()
panda:综合训练
对于这一组电影数据,如果我们想rating,runtime的分布情况,应该如何呈现数据?
对于这一组电影数据,如果我们希望统计电影分类(genre)的情况,应该如何处理数据?
思路:重新构造一个全为0的数组,列名为分类,如果某一条数据中分类出现过,就让0变为1
import pandas as pd from matplotlib import pyplot as plt import numpy as np file_path = "./IMDB-Movie-Data.csv" df = pd.read_csv(file_path) # 统计分类的列表 temp_list = df[\'Genre\'].str.split(",").tolist() # print(temp_list) genre_list = list(set([i for j in temp_list for i in j])) # print(genre_list) # 构造全为0的数组 zeros_df = pd.DataFrame(np.zeros((df.shape[0], len(genre_list))), columns=genre_list) # print(zeros_df) # 给每个电影出现的位置赋值1 for i in range(df.shape[0]): zeros_df.loc[i, temp_list[i]] = 1 # 统计每个分类的电影的数量和 genre_count = zeros_df.sum(axis=0) # print(genre_count) # 排序 genre_count = genre_count.sort_values() # 画图 _x = genre_count.index _y = genre_count.values plt.figure(figsize=(20, 8), dpi=80) # plt.bar(range(len(_x)), _y) # plt.xticks(range(len(_x)), _x) plt.bar(_x,_y) plt.show()
模拟退火学习
案例一
用matlab的做法:1.写一份函数 2.命令行打开工具箱 optimtool 3.模型选择 simulannealbnd
案例二
import matplotlib.pyplot as plt import pandas as pd demo_func = lambda x: x[0] ** 2 + (x[1] - 0.05) ** 2 + x[2] ** 2 from sko.SA import SA sa = SA(func=demo_func, x0=[1,1,1], T_max=1, T_min=1e-9, L=500, max_stay_counter=100) best_x, best_y = sa.run() print(\'best_x:\', best_x, \'best_y\', best_y) plt.plot(pd.DataFrame(sa.best_x_history).cummin(axis=0), pd.DataFrame(sa.best_y_history).cummin(axis=0)) plt.show()
案例三
直接手动限定范围找到的最值
from math import sin from math import cos from sko.SA import * import matplotlib.pyplot as plt import pandas as pd import math from scipy import optimize # demo_func = lambda x: x + 5*sin(5*x) + 2*cos(4*x) def demo_func(x): return math.sin(x * x) + 2.0 * math.cos(2.0 * x) # 最值点 minimum_x = optimize.fminbound(demo_func, 1e-7, 13) minimum_y = demo_func(minimum_x) maxmun_x = optimize.fminbound(lambda x:-demo_func(x), 6, 7) maxmun_y = demo_func(maxmun_x) sa = SA(func=demo_func, x0=[2], T_max=13, L=1000, max_stay_counter=150) best_x, best_y = sa.run() print(sa.best_y_history) print(\'best_x: {} \nbest_y:{}\'.format(best_x, best_y)) _x = np.arange(0, 13, 0.01) _y = [demo_func(i) for i in _x] plt.rcParams[\'font.sans-serif\'] = [\'SimHei\'] # 解决中文显示 plt.rcParams[\'axes.unicode_minus\'] = False # 解决符号无法显示 plt.annotate("最小值点:{:.3},{:}".format(minimum_x, minimum_y), (minimum_x, minimum_y)) plt.annotate("最大值点:{:.3},{:}".format(maxmun_x, maxmun_y), (maxmun_x, maxmun_y)) plt.plot(_x, _y) # plt.plot(pd.DataFrame(sa.best_x_history).cummin(axis=0)) plt.show()
用网上的一个师傅的脚本跑最大值
import math import numpy as np import matplotlib.pyplot as plt import random class SA(object): def __init__(self, interval, tab=\'min\', T_max=10000, T_min=1, iterMax=1000, rate=0.95): self.interval = interval # 给定状态空间 - 即待求解空间 self.T_max = T_max # 初始退火温度 - 温度上限 self.T_min = T_min # 截止退火温度 - 温度下限 self.iterMax = iterMax # 定温内部迭代次数 self.rate = rate # 退火降温速度 ############################################################# # self.x_seed = random.uniform(interval[0], interval[1]) # 解空间内的种子 self.x_seed=2 self.tab = tab.strip() # 求解最大值还是最小值的标签: \'min\' - 最小值;\'max\' - 最大值 ############################################################# self.solve() # 完成主体的求解过程 self.display() # 数据可视化展示 def solve(self): temp = \'deal_\' + self.tab # 采用反射方法提取对应的函数 if hasattr(self, temp): deal = getattr(self, temp) else: exit(\'>>>tab标签传参有误:"min"|"max"<<<\') x1 = self.x_seed T = self.T_max while T >= self.T_min: for i in range(self.iterMax): f1 = self.func(x1) delta_x = random.random() * 2 - 1 if self.interval[0] <= x1 + delta_x <= self.interval[1]: # 将随机解束缚在给定状态空间内 x2 = x1 + delta_x else: x2 = x1 - delta_x f2 = self.func(x2) delta_f = f2 - f1 x1 = deal(x1, x2, delta_f, T) T *= self.rate self.x_solu = x1 # 提取最终退火解 self.y_solu =self.func(x1) def func(self, x): # 状态产生函数 - 即待求解函数 # value = np.sin(x ** 2) * (x ** 2 - 5 * x) # return value return np.sin(x * x) + 2.0 * np.cos(2.0 * x) def p_min(self, delta, T): # 计算最小值时,容忍解的状态迁移概率 probability = np.exp(-delta / T) return probability def p_max(self, delta, T): probability = np.exp(delta / T) # 计算最大值时,容忍解的状态迁移概率 return probability def deal_min(self, x1, x2, delta, T): if delta < 0: # 更优解 return x2 else: # 容忍解 P = self.p_min(delta, T) if P > random.random(): return x2 else: return x1 def deal_max(self, x1, x2, delta, T): if delta > 0: # 更优解 return x2 else: # 容忍解 P = self.p_max(delta, T) if P > random.random(): return x2 else: return x1 def display(self): print(\'seed: {}\nsolution: {},{}\'.format(self.x_seed, self.x_solu,self.y_solu)) plt.figure(figsize=(6, 4)) x = np.linspace(self.interval[0], self.interval[1], 300) y = self.func(x) plt.plot(x, y, \'g-\', label=\'function\') plt.plot(self.x_seed, self.func(self.x_seed), \'bo\', label=\'seed\') plt.plot(self.x_solu, self.func(self.x_solu), \'r*\', label=\'solution\') plt.title(\'solution = {},{}\'.format(self.x_solu,self.y_solu)) plt.xlabel(\'x\') plt.ylabel(\'y\') plt.legend() # plt.savefig(\'SA.png\', dpi=500) plt.show() plt.close() if __name__ == \'__main__\': SA([0,10], tab=\'max\',rate=0.8) # SA([-5, 5], \'max\')
用matlab工具箱跑最大值,x的值没什么问题,y值怎么调都是负的
案例四
import math import numpy as np import matplotlib.pyplot as plt import random N = 1144645 people_data = [ [130715, 65, 0, 0.04, 5228.6, 0.04], [281533, 55, 12, 0.08, 22522.64, 0.005], [457895, 30, 36, 0.12, 54947.4, 0.02], [274502, 2, 12, 0.16, 43920.32, 0.08], ] coefficient_of_weight_l=list() coefficient_of_weight_m=list() class SA(object): def __init__(self, interval, tab=\'min\', T_max=10000, T_min=1, iterMax=1000, rate=0.95): self.interval = interval # 给定状态空间 - 即待求解空间 self.T_max = T_max # 初始退火温度 - 温度上限 self.T_min = T_min # 截止退火温度 - 温度下限 self.iterMax = iterMax # 定温内部迭代次数 self.rate = rate # 退火降温速度 self.tab = tab.strip() # 求解最大值还是最小值的标签: \'min\' - 最小值;\'max\' - 最大值 self.solve() # 完成主体的求解过程 self.display() # 数据可视化展示 def solve(self): temp = \'deal_\' + self.tab # 采用反射方法提取对应的函数 if hasattr(self, temp): deal = getattr(self, temp) else: exit(\'>>>tab标签传参有误:"min"|"max"<<<\') T = self.T_max x1=list() while T >= self.T_min: for i in range(self.iterMax): x1 = self.get_one_piece(self.T_max) f1 = self.func(x1) x2=self.get_one_piece(self.T_max) # delta_x = int(random.random() * 20 - 1) # for i in range(len(x1)): # if self.interval[0] <= x1[i] + delta_x <= self.interval[1]: # 将随机解束缚在给定状态空间内 # x2.append(x1[i] + delta_x) # else: # x2.append(x1[i] - delta_x) f2 = self.func(x2) delta_f = f2 - f1 x1 = deal(x1, x2, delta_f, T) T *= self.rate self.x_solu = x1 # 提取最终退火解 self.y_solu = self.func(x1) def get_one_piece(self, X): x = list() s = 0 for i in range(4): while True: t=random.randint(0, X - s) if t<=people_data[i][0]*people_data[i][3] and t<N: break x.append(t) s += x[i] return x def func(self, x): # 状态产生函数 - 即待求解函数 global coefficient_of_weight_l,coefficient_of_weight_m coefficient_of_weight_l = [random.random()*5, random.random()*5, random.random()*5, random.random()*5] coefficient_of_weight_m = [random.random()*5, random.random()*5, random.random()*5, random.random()*5] result = -np.inf for i in range(4): sum_one = x[i] * people_data[i][1] * coefficient_of_weight_l[i] sum_two = x[i] * people_data[i][2] * coefficient_of_weight_m[i] if result < sum_one+sum_two: result = sum_one+sum_two return result def p_min(self, delta, T): # 计算最小值时,容忍解的状态迁移概率 probability = np.exp(-delta / T) return probability def p_max(self, delta, T): probability = np.exp(delta / T) # 计算最大值时,容忍解的状态迁移概率 return probability def deal_min(self, x1, x2, delta, T): if delta < 0: # 更优解 return x2 else: # 容忍解 P = self.p_min(delta, T) if P > random.random(): return x2 else: return x1 def deal_max(self, x1, x2, delta, T): if delta > 0: # 更优解 return x2 else: # 容忍解 P = self.p_max(delta, T) if P > random.random(): return x2 else: return x1 def display(self): print("最优解:{}".format(self.y_solu)) for i in range(4): print("群体{}分配的疫苗数:{}".format(i, self.x_solu[i])) print("权系数l:{}".format(coefficient_of_weight_l)) print("权系数m:{}".format(coefficient_of_weight_m)) if __name__ == \'__main__\': for i in range(20): SA([0, 10000], tab=\'max\', rate=0.95) # SA([-5, 5], \'max\')
matlab学习
用法笔记
- 每行语句后面加分号表示不显示运行结果;区分行
- 多行注释快捷键ctrl+r,取消注释ctrl+t
- clear:清除工作区内所有的变量,clc清除命令行窗口中的所有文本
- 描述列向量:a=[1;2;3]
- 输出和输入函数(disp 和 input)
- 两个字符串的合的两种方法:
- strcat(str1,str2……,strn)
- [str 1,str 2,……, str n]或[str1 str2 …… strn]
- num2str 将数字转换为字符串
常用函数
- sum函数
- (1)如果是向量(无论是行向量还是列向量),都是直接求和
- (2)如果是矩阵,则需要根据行和列的方向作区分
- a=sum(x); %按列求和(得到一个行向量)
- a=sum(x,2); %按行求和(得到一个列向量)
- a=sum(x(:));%对整个矩阵求和
- normrnd(0,1):生成一个服从正态分布的随机数(第一个表示均值,第二个表示标准差)
- exprnd(5):生成一个均值位5的指数分布随机数
- mean([1,2,3]):用来求均值的函数
- tic;;toc:计算代码运行时长
论文写作
公式上浮
法一:
法二:
公式自动编号,选择autonum
参考文献的写作方法
标准格式–》网站上复制引用
地图可视化总结
- 可以把下载好的SVG地图直接拖到PPT里面,然后取消组合,接下来自己修改各形状的填充颜色即可。
- 下面这个网站可以导出世界各个国家的SVG地图格式(注意:下载的地图可能不完整,使用时应该注意,以免引起误会):https://pixelmap.amcharts.com/
- 下面这个网站可以导出中国各省市的SVG地图格式(搜索:地图选择器):http://datav.aliyun.com/tools/atlas/
第8讲.图论最短路径问题
用matlab画图
%% 注意:以下代码需要较新版本的matlab才能运行(最好是2016版本及以上哦) % 如果运行出错请下载新版的matlab代码再运行 %% Matlab作无向图 % (1)无权重(每条边的权重默认为1) % 函数graph(s,t):可在 s 和 t 中的对应节点之间创建边,并生成一个图 % s 和 t 都必须具有相同的元素数;这些节点必须都是从1开始的正整数,或都是字符串元胞数组。 s1 = [1,2,3,4]; t1 = [2,3,1,1]; G1 = graph(s1, t1); plot(G1) % 注意哦,编号最好是从1开始连续编号,不要自己随便定义编号 s1 = [1,2,3,4]; t1 = [2,3,1,1]; G1 = graph(s1, t1); plot(G1) % 注意字符串元胞数组是用大括号包起来的哦 s2 = {\'学校\',\'电影院\',\'网吧\',\'酒店\'}; t2 = {\'电影院\',\'酒店\',\'酒店\',\'KTV\'}; G2 = graph(s2, t2); plot(G2, \'linewidth\', 2) % 设置线的宽度 % 下面的命令是在画图后不显示坐标 % set( gca, \'XTick\', [], \'YTick\', [] ); % (2)有权重 % 函数graph(s,t,w):可在 s 和 t 中的对应节点之间以w的权重创建边,并生成一个图 s = [1,2,3,4]; t = [2,3,1,1]; w = [3,8,9,2]; G = graph(s, t, w); plot(G, \'EdgeLabel\', G.Edges.Weight, \'linewidth\', 2) % set( gca, \'XTick\', [], \'YTick\', [] ); %% Matlab作有向图 % 无权图 digraph(s,t) s = [1,2,3,4,1]; t = [2,3,1,1,4]; G = digraph(s, t); plot(G) set( gca, \'XTick\', [], \'YTick\', [] ); % 有权图 digraph(s,t,w) s = [1,2,3,4]; t = [2,3,1,1]; w = [3,8,9,2]; G = digraph(s, t, w); plot(G, \'EdgeLabel\', G.Edges.Weight, \'linewidth\', 2) set( gca, \'XTick\', [], \'YTick\', [] );
用matlab自带的迪杰斯特拉算法求最短路
%% 注意:以下代码需要较新版本的matlab才能运行(最好是2016版本及以上哦) % 如果运行出错请下载新版的matlab代码再运行 % 注意哦,Matlab中的图节点要从1开始编号,所以这里把0全部改为了9 % 编号最好是从1开始连续编号,不要自己随便定义编号 s = [9 9 1 1 2 2 2 7 7 6 6 5 5 4]; t = [1 7 7 2 8 3 5 8 6 8 5 3 4 3]; w = [4 8 3 8 2 7 4 1 6 6 2 14 10 9]; G = graph(s,t,w); plot(G, \'EdgeLabel\', G.Edges.Weight, \'linewidth\', 2) set( gca, \'XTick\', [], \'YTick\', [] ); [P,d] = shortestpath(G, 9, 4) %注意:该函数matlab2015b之后才有哦 % 在图中高亮我们的最短路径 myplot = plot(G, \'EdgeLabel\', G.Edges.Weight, \'linewidth\', 2); %首先将图赋给一个变量 highlight(myplot, P, \'EdgeColor\', \'r\') %对这个变量即我们刚刚绘制的图形进行高亮处理(给边加上r红色) % 求出任意两点的最短路径矩阵 D = distances(G) %注意:该函数matlab2015b之后才有哦 D(1,2) % 1 -> 2的最短路径 D(9,4) % 9 -> 4的最短路径 % 找出给定范围内的所有点 nearest(G,s,d) % 返回图形 G 中与节点 s 的距离在 d 之内的所有节点 [nodeIDs,dist] = nearest(G, 2, 10) %注意:该函数matlab2016a之后才有哦
作业题
s = [1 1 1 2 3 3 4 5 5 5 5 6 6 7 9 9]; t = [2 4 3 5 2 4 6 4 6 7 8 5 7 8 5 8]; w = [6 1 3 1 2 2 10 6 4 3 6 10 2 4 2 3]; G = digraph(s,t,w); plot(G, \'EdgeLabel\', G.Edges.Weight, \'linewidth\', 2) set( gca, \'XTick\', [], \'YTick\', [] ); [P,d] = shortestpath(G, 1, 8) %计算1->8的最短路 myplot = plot(G, \'EdgeLabel\', G.Edges.Weight, \'linewidth\', 2); %首先将图赋给一个变量 highlight(myplot, P, \'EdgeColor\', \'r\') %对这个变量即我们刚刚绘制的图形进行高亮处理(给边加上r红色) % 求出任意两点的最短路径矩阵 D = distances(G) D(1,8)
P = 1 3 2 5 8 d = 12 D = 1 至 5 列 0 5 3 1 6 Inf 0 Inf 7 1 Inf 2 0 2 3 Inf Inf Inf 0 20 Inf Inf Inf 6 0 Inf Inf Inf 16 10 Inf Inf Inf Inf Inf Inf Inf Inf Inf Inf Inf Inf Inf 8 2
6 至 9 列 11 9 12 Inf 11 4 7 Inf 12 6 9 Inf 10 12 16 Inf 10 3 6 Inf 0 2 6 Inf Inf 0 4 Inf Inf Inf 0 Inf 12 5 3 0 ans = 12
更新6 floyd弗洛伊德算法
主函数
% PPT第七页的例子 clc; %% 首先将图转换为权重邻接矩阵D n = 5; %一共五个节点 D = ones(n) ./ zeros(n); % 全部元素初始化为Inf for i = 1:n D(i,i) = 0; % 主对角线元素为0 end D(1,2) = 3; D(1,3) = 8; D(1,5) = -4; D(2,5) = 7; D(2,4) = 1; D(3,2) = 4; D(4,3) = -5; D(5,4) = 6; D(4,1) = 2; %% 调用Floyd_algorithm函数求解 [dist,path] = Floyd_algorithm(D) %print_path(path,dist,1,5); %print_path(path,dist,1,4); %print_path(path,dist,3,1); %clc %disp(\'下面我们打印任意两点之间的最短距离:\') %print_all_path(D)
print_path函数
function [] = print_path(path,dist,i,j) %% 该函数的作用是打印从i到j经过的最短路径 % 输入: % path是使用floyd算法求出来的路径矩阵 % dist是使用floyd算法求出来的最短距离矩阵 % i是起始节点的编号 % j是终点节点的编号 % 输出:无 if i == j warning(\'起点和终点相同,请检查后重新输入\') % 在屏幕中提示警告信息 return; % 不运行下面的语句,直接退出函数 end if path(i,j) == j % 如果path(i,j) = j,则有两种可能: % (1)如果dist(i,j) 为 Inf , 则说明从i到j没有路径可以到达 if dist(i,j) == Inf disp([\'从\',num2str(i),\'到\',num2str(j),\'没有路径可以到达\']) % (2)如果dist(i,j) 不为 Inf , 则说明从i到j可直接到达,且为最短路径 else disp([\'从\',num2str(i),\'到\',num2str(j),\'的最短路径为\']) disp([num2str(i),\' ---> \',num2str(j)]) disp([\'最短距离为\',num2str(dist(i,j))]) end else % 如果path(i,j) ~= j,则说明中间经过了其他节点: k = path(i,j); result = [num2str(i),\' ---> \']; % 初始化要打印的这个字符串 while k ~= j % 只要k不等于j, 就一直循环下去 result = [result , num2str(k) , \' ---> \' ]; % i先走到k这个节点处 k = path(k,j); end result = [result , num2str(k)]; disp([\'从\',num2str(i),\'到\',num2str(j),\'的最短路径为\']) disp(result) disp([\'最短距离为\',num2str(dist(i,j))]) end end
Floyd_algorithm
function [dist,path] = Floyd_algorithm(D) %% 该函数用于求解一个权重邻接矩阵任意两个节点之间的最短路径 % 输入: % D是权重邻接矩阵 % 输出: % dist是最短距离矩阵,其元素dist_ij表示表示i,j两个节点的最短距离 % path是路径矩阵,其元素path_ij表示起点为i,终点为j的两个节点之间的最短路径要经过的节点 n = size(D,1); % 计算节点的个数 % 初始化dist矩阵 dist = D; % 下面我们来初始化path矩阵 path = zeros(n); for j = 1:n path(:,j) = j; % 将第j列的元素变为j end for i = 1:n path(i,i) = -1; % 将主对角线元素变为-1 end % 下面开始三个循环 for k=1:n % 中间节点k从1- n 循环 for i=1:n % 起始节点i从1- n 循环 for j=1:n % 终点节点j从1-n 循环 if dist(i,j)>dist(i,k)+dist(k,j) % 如果i,j两个节点间的最短距离大于i和k的最短距离+k和j的最短距离 dist(i,j)=dist(i,k)+dist(k,j); % 那么我们就令这两个较短的距离之和取代i,j两点之间的最短距离 path(i,j)=path(i,k); % 起点为i,终点为j的两个节点之间的最短路径要经过的节点更新为path(i,k) % 注意,上面一行语句不能写成path(i,j) = k; 这是网上很多地方都容易犯的错误,在PPT11页中会告诉大家为什么不能这么写 end end end end end
python版本
\'\'\' @Time : 2021-01-24 9:28 @Author : laolao @FileName: 12.py \'\'\' import numpy as np class floyd(): def __init__(self, matrix): self.n = len(matrix) self.distance = np.matrix(np.ones((self.n, self.n)) * np.inf).tolist() self.sequence = np.matrix(np.ones((self.n, self.n))).tolist() for i in range(self.n): for j in range(self.n): if i == j: self.distance[i][j] = 0 self.sequence[i][j] = -1 else: self.distance[i][j] = matrix[i][j] self.sequence[i][j] = j def calculate(self): for k in range(self.n): for i in range(self.n): for j in range(self.n): if self.distance[i][k] + self.distance[k][j] < self.distance[i][j]: self.distance[i][j] = self.distance[i][k] + self.distance[k][j] self.sequence[i][j] = self.sequence[i][k] return self.distance, self.sequence def out_put_path(self, i, j): if i==j: print("起点与终点相同无意义") return 0 if self.sequence[i][j]==j: if self.distance[i][j]==np.inf: print("{}->{}不可达".format(i,j)) else: print("最短路径:\n{}->{}\n最短距离:{}".format(i,j,self.distance[i][j])) else: k=self.sequence[i][j] res="{}->".format(i) while k!=j: res+="{}->".format(k) k=self.sequence[k][j] res+="{}".format(j) print("最短路径:\n{}\n最短距离:{}".format(res, self.distance[i][j])) if __name__ == \'__main__\': m = [ [np.inf, 3, 8, np.inf, -4], [np.inf, np.inf, np.inf, 1, 7], [np.inf, 4, np.inf, np.inf, np.inf], [2, np.inf, -5, np.inf, np.inf], [np.inf, np.inf, np.inf, 6, np.inf] ] lao = floyd(m) d, s = lao.calculate() lao.out_put_path(2,0)
蒙特卡罗模拟
作业1
def homework_one_X(): n=6000 m = 0 people = 4 for i in range(n): L = torch.randperm(people).numpy()-np.arange(people) if len(np.where(L==0)[0]) ==0 : m+=1 print("蒙特卡罗模拟的:{:.10f} 真实值:{:.10f}".format(n/m.real,math.e))
def homework_one(): n =4000 one=-1 sum=0 for i in range(n): one*=-1 sum+=one/math.factorial(i).real print("蒙特卡罗模拟的:{:.10f} 真实值:{:.10f}".format(1/sum.real,math.e))
作业2
\'\'\' @Time : 2021-01-26 16:05 @Author : laolao @FileName: 1.py \'\'\' import math import numpy as np import pandas as pd from decimal import Decimal import random import torch def homework(): n=10000 sum=0 for i in range(n): money=0 level=1 while level!=5: one = random.randint(0, 100) money += 10000 if level==1: if 65 <= one < 85: # print("成功升到2级,此时花费:{}".format(money)) level=2 elif one >=85 and one <95: # print("成功升到3级,此时花费:{}".format(money)) level=3 elif one >=95 and one <100: # print("成功升到4级,此时花费:{}".format(money)) level=4 # else: # print("没有升级,此时花费:{}".format(money)) elif level==2: if one >= 40 and one < 65: # print("下降到1级,此时花费:{}".format(money)) level = 1 elif one >= 65 and one < 85: # print("成功升到3级,此时花费:{}".format(money)) level = 3 elif one >= 85 and one < 95: # print("成功升到4级,此时花费:{}".format(money)) level = 4 elif one >=95 and one <=100: # print("成功升到5级,此时花费:{}".format(money)) level=5 # else: # print("没有升级,此时花费:{}".format(money)) elif level==3: if one >= 40 and one < 60: # print("下降到2级,此时花费:{}".format(money)) level = 2 elif one >= 60 and one < 80: # print("成功升到4级,此时花费:{}".format(money)) level = 4 elif one >= 80 and one < 90: # print("下降到1级,此时花费:{}".format(money)) level = 1 elif one >= 90 and one <= 100: # print("成功升到5级,此时花费:{}".format(money)) level = 5 # else: # print("没有升级,此时花费:{}".format(money)) elif level==4: if one >= 40 and one < 70: # print("下降到3级,此时花费:{}".format(money)) level = 3 elif one >= 70 and one < 80: # print("下降到2级,此时花费:{}".format(money)) level = 2 elif one >= 80 and one < 100: # print("成功升到5级,此时花费:{}".format(money)) level = 5 # else: # print("没有升级,此时花费:{}".format(money)) sum+=money print("{}\n升级到5级平均花费:{}".format(\'*\'*50,sum/n)) if __name__ == \'__main__\': homework()
作业3
\'\'\' @Time : 2021-01-26 16:05 @Author : laolao @FileName: 1.py \'\'\' import math import numpy as np import numpy.matlib import pandas as pd from decimal import Decimal import random import torch def homework(): r = np.inf c=0 n=10000 for i in range(n): x1=np.random.uniform(0,16) x2=np.random.uniform(0,8) if 3*x1+x2>9 and x1+2*x2<16: c+=1 t = 2*(x1**2)+x2**2-x1*x2-8*x1-3*x2 # print(t) if r>t: r=t print("蒙特卡洛模拟:{}".format(r)) if __name__ == \'__main__\': for i in range(10): homework()
作业4
\'\'\' @Time : 2021-01-26 16:05 @Author : laolao @FileName: 1.py \'\'\' import math import numpy as np import numpy.matlib import pandas as pd from decimal import Decimal import random import torch def homework(): T = 10000000 t=0 cost_one = 0 lifetime = np.array([np.random.randint(1000, 2000), np.random.randint(1000, 2000), np.random.randint(1000, 2000), np.random.randint(1000, 2000)]) while t<T: min_one = min(lifetime) t += min_one+1 lifetime -= min_one cost_one += 20+10 for i in range(4): if lifetime[i]==0: lifetime[i]=np.random.randint(1000,2000) cost_two=0 t=0 while t<T: lifetime = np.array([np.random.randint(1000, 2000), np.random.randint(1000, 2000), np.random.randint(1000, 2000),np.random.randint(1000, 2000)]) min_one = min(lifetime) t += min_one + 2 cost_two+=2*20+10*4 print("总时间{}内\n方案一花费:{}\n方案二花费:{}\n".format(T,cost_one,cost_two)) if __name__ == \'__main__\': for i in range(5): homework()
SPSS缺失值处理
均值处理缺失值
适用条件:1.缺失值低于百分之5 2.只适用于连续性数值变量或者离散型数值变量(性别这种分类变量就不行)。序列平均值=均值=最为准确的替换方案
中位数填补缺失值
适用条件:等级变量的缺失填充(年龄段)
1.计算中位数 2.根据报告里得到的中位数对缺失的数据进行手动填充
众数填补缺失值
适用于无序分类变量(兴趣爱好,性别,专业)
回归插补法
是把缺失属性作为因变量,其他相关属性作为自变量,利用他们之间的关系建立回归模型的来预测缺失值,以此完成缺失值插补的方法(自变量与因变量之间有因果关系,自变量不能有缺失)
期望最大化法
1.用期望值替代缺失值 2.对替换好的数据进行极大似然估计
插值法
clear;clc; % n维数据的插值 load data4; new_x= 3:0.01:6 % 画第一张图 p1 = pchip (x1, y11, new_x); p2 = pchip (x1, y12, new_x); p3 = pchip (x1, y13, new_x); p4 = pchip (x1, y14, new_x); fig = subplot(3,1,1); left_color = [0 0 0]; right_color = [0 0 0]; set(fig,\'defaultAxesColorOrder\',[left_color; right_color]); yyaxis left plot(new_x, p1, \'r-\') ylabel(\'群体i分得疫苗数\'); %%设置纵坐标 yyaxis right plot(new_x,p2,\'g-\',new_x,p3,\'b-\',new_x,p4,\'y-\') legend("群体1","群体2","群体3","群体4",\'Location\',\'northwest\') xlabel(\'lg(m/l)\'); %%设置横坐标 title(\'lg寿命l=-2\'); %%设置标题 hold on; % 画第二张图 p1 = pchip (x1, y21, new_x); p2 = pchip (x1, y22, new_x); p3 = pchip (x1, y23, new_x); p4 = pchip (x1, y24, new_x); fig = subplot(3,1,2); left_color = [0 0 0]; right_color = [0 0 0]; set(fig,\'defaultAxesColorOrder\',[left_color; right_color]); yyaxis left plot(new_x, p1, \'r-\') ylabel(\'群体i分得疫苗数\'); %%设置纵坐标 yyaxis right plot(new_x,p2,\'g-\',new_x,p3,\'b-\',new_x,p4,\'y-\') legend("群体1","群体2","群体3","群体4",\'Location\',\'northwest\') xlabel(\'lg(m/l)\'); %%设置横坐标 hold on; % 画第三张图 p1 = pchip (x1, y31, new_x); p2 = pchip (x1, y32, new_x); p3 = pchip (x1, y33, new_x); p4 = pchip (x1, y34, new_x); fig = subplot(3,1,3); left_color = [0 0 0]; right_color = [0 0 0]; set(fig,\'defaultAxesColorOrder\',[left_color; right_color]); yyaxis left plot(new_x, p1, \'r-\') ylabel(\'群体i分得疫苗数\'); %%设置纵坐标 yyaxis right plot(new_x,p2,\'g-\',new_x,p3,\'b-\',new_x,p4,\'y-\') legend("群体1","群体2","群体3","群体4",\'Location\',\'northwest\') xlabel(\'lg(m/l)\'); %%设置横坐标