pycharm的console/cmd

  • 清除一个变量:del 变量名
  • 清楚所有变量:先输入reset ,回车后再输入y
  • 在cmd里查看包的位置,输入pip show 包名
  • 在cmd里删除包,pip uninstall 包名

技巧

  1. #显示所有列
  2. pd.set_option('display.max_columns', None)
  3. #显示所有行
  4. pd.set_option('display.max_rows', None)
  5. #dataframe的日期只提取年月
  6. dataframe.dt.strftime('%Y-%m')

bug

  • no model found

解决办法:

  1. import sys
  2. sys.path.append(r'上一级的绝对路径')

语法基础

print(f’’):格式化输出,‘’里变量用方括号括起
在console中用”def 变量名”来删除变量

  • 在变量前后使用“?”,可以显示对象信息

In [10]: print?
Docstring:
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

  • 强行终止:代码运行时按Ctrl-C,无论是%run或长时间运行命令,都会导致KeyboardInterrupt。这会导致几乎所有Python程序立即停止,除非一些特殊情况。
  • python - 图1

python - 图2

  • Python的语句不需要用分号结尾。但是,分号却可以用来给同在一行的语句切分
  • python - 图3

错误处理

  1. try:
  2. # 语句
  3. except Exception as e:
  4. print(e)
  5. else:
  6. # 语句

输入输出

输入:x = input([‘输入提示’])

  1. # 输入获得两个字符串(如输入abd def或abc,def)
  2. x,y=input('Input: ').split()
  3. x,y=input('Input: ').split(',')
  4. # 输入获得两个整数
  5. x,y = eval(input('Input: '))
  6. # 输入后获得一个元素均为数值型的列表
  7. lst = list(eval(input('Input: '))) #输入12,3.4,456
  8. lst = eval(input('Input: ')) # 输入[12,3.4,456]

输出:print(object1,obk=ject2,…,sep = ‘’, end = ‘\n’)
sep表示输出对象之间的分隔符,默认为空格;参数end的默认值为’\n’,表示print()函数输出完成后自动换行

  1. # 在输出数据中加入一个空白分隔符
  2. print(x,y,sep = ',') # 用逗号分隔
  3. print(x),print(y) # 换行
  4. #循环输出所有的数据并放在同一行输出
  5. for i in range(1,5):
  6. print(i, end=' ')
  7. #格式化输出
  8. print(format.)
  9. print(format_string.format(arguments_to_convert))

格式转换

for循环

1、用for遍历字典

  1. a={'':,'':}
  2. for i in a.keys():
  3. #操作
  4. for i in a.values():
  5. #操作
  6. #同时提出键和值
  7. a.items()

数据结构

顺序 能否更改 能否重复 表达 有无索引 其他
列表
list
1)[…];
2)创建方法:list(range());
a=[i**2 for i in range(0,5)]
1、排序。从小到大:a.sort();从大到小:a.sort(reverse=True)
2、一个列表可以放任何类型的数据;列表里面可以包含列表
元组 有序 不能 ( , , , )
e.g:In: tuple([4, 0, 2])
Out: (4, 0, 2)
可以用方括号”[ ]”访问元组中的元素 1、用tuple可以将任意序列或迭代器转换成元组
2、可以用加号运算符将元组串联起来
In: (4, None, ‘foo’) + (6, 0)
Out: (4, None, ‘foo’, 6, 0)
3、简便的替换
a,b=b,a
集合 无序 不能 不能 可以把它当做字典,但是只有键没有值
字符串 1、字符串只能和字符串相加,str()
  • range(start, end, step),返回一个list对象也就是range.object,起始值为start,终止值为end,但不含终止值,步长为step。只能创建int型list。
  • arange(start, end, step),与range()类似,也不含终止值。但是返回一个array对象。需要导入numpy模块(import numpy as np或者from numpy import*),并且arange可以使用float型数据。
  • 切片:左闭右开
  • 查看元素类型:type(变量名)
  • range(起始,终止,步长),但终止值不包含,用list可转化为列表
  • python的所有编号都是从0开始的

    1. seq = [7, 2, 3, 7, 5, 6, 0, 1]
    2. # 隔取
    3. In [81]: seq[::2]
    4. Out[81]: [7, 3, 3, 6, 1]
    5. # 逆序
    6. In [82]: seq[::-1]
    7. Out[82]: [1, 0, 6, 5, 3, 6, 3, 2, 7]

    类与继承

    创建父类
    class person:
    #若加上:slots=(‘fname’,’lname’) 则表明init里只能创建fname和lname这两个参数,如果再加上其他的参数则运行错误
    def init(self, fname, lname):
    self.firstname = fname
    self.lastname = lname
    def printname(self):
    print(self.firstname , self.lastname)
    #子类
    class student(person): #表示继承父类
    def init(self,fname,lname,year): #若不写super(),则子类的init会覆盖父类的init
    super().init(fname,lname)
    self.graduationyear = year #添加year参数
    x=student(“elon”,’musk’,2016)
    print(x.graduationyear)
    #2016

    numpy

  • 创建数组:np.array([···]);表示先创建一个列表[],然后把用np.array列表转化为np里的数组

  • python里的矩阵用np里的二维数组表示
  • np.concatenate((要合并的矩阵(可以多个)),axis=) #axis=1按行合并;axis=0 按列合并
  • 不等量分割: np.array_split
  • 关于axis这个属性的定义是基于数组shape的这个属性,它是一个python元组,对于二维书而言,axi
  • np.array生成数组,用np.dot()表示矩阵乘积;(*)号或np.multiply()表示点乘

    np.mat生成数组,(*)和np.dot()相同,点乘只能用np.multiply()
    总结下来, dot()一定是点乘,multiply()一定是对应位置的元素相乘。

  • 数据切片:https://www.jianshu.com/p/15715d6f4dad

    1. # 从Excel导入文件.但一般用pandas导入
    2. import numpy as np
    3. a = np.genfromtext(r':\',dytpe=,delimiter=',',skip=)
    4. #delimiter表示分隔符号
    5. # skip:要不要跳过第一行,为0表示不跳过数据的首行;为1表示从第二行开始输入

    pandas

    dataframe:行的索引是index,列的索引是columns,数据是numpy的数据 ```python df=pd.DataFrame(a ,index=b, columns=c)

    a是数据,如np.random.randn(8, 4),c是列名

df[[‘column1’,’culumn2’,…]] #选出列 df[:2] #选出前两行

df.loc[:,’’] #[]左边为index,右边为column。 loc有点像excel的鼠标左键,可以随意拉动需要的数据

  1. 1pd.DataFrame(数据,index=.columns=)<br />也可以用字典,字典的索引是列标<br />将dataframe导出为excel : xxx.to_excel('XX.xls')<br />#select by index<br />.col 以标签的形式选择<br />#select by position: iloc<br />#mixed selection: ix<br /># 0是对行处理(以行为对象),1是对列处理<br />#isnull()看是否缺失<br />#fillna()
  2. - py普通的切片不包括尾部数值,但Series不同
  3. <a name="cnPLD"></a>
  4. ## 数据分析
  5. <a name="HjjS1"></a>
  6. ### 数据探索与清洗
  7. ```python
  8. import pandas as pd
  9. data = pd.read_csv(".txt",sep='',names=[])
  10. '''
  11. 1\关联两个表数据 =pd.merge(data1,data2)
  12. 2\提取所需要的列 =pd.DataFrame(data,columns=[])
  13. 3\查看前num行数据 data.head(num)
  14. '''
  15. '''假设数据集为data'''
  16. # 首先查看数据信息
  17. data.shape # 查看数据规模——多少行,多少列
  18. data.info() # 查看整体数据信息,包括每个字段的名称、非空数量、字段的数据类型
  19. data.describe() # 查看数据分布
  20. #数据清理
  21. data['ColName'].filna('ReplaceName',inplace='') # 空值处理
  22. data['ColName']=data['ColName'].astype(datatype) # 转换数据类型如str,float

数据分析

  1. data.groupby('ColName').sum().sort_values('ColName2',ascending=True/False).head(num)

matplotlib

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. # 有了sharex和sharey会比较好看:不会重合,有空隙
  4. '''fig, axs = plt.subplots(2,2,sharex=True,sharey=True) # a figure with a 2x2 grid of Axes :(0,0)
  5. x = np.linspace(0,2,100)
  6. axs[1,1].plot(x,x,label='linear')
  7. axs[1,0].plot(x,x**2,label='quadratic')
  8. axs[1,1].set_xlabel('xlabel')
  9. axs[1,1].set_ylabel('ylabel')
  10. axs[1,1].set_title('Simple Plot')
  11. axs[1,1].legend()
  12. plt.show()
  13. '''
  14. # method 2
  15. ''' fig = plt.figure()
  16. ax1 = fig.add_subplot(2,2,1)'''
  17. # method 3
  18. '''fig, (ax1, ax2) = plt.subplots(1, 2)
  19. my_plotter(ax1, data1, data2, {'marker': 'x'})'''
  20. data = {'a' : np.arange(50),
  21. 'b' : np.random.randint(0,50,50),
  22. 'd': np.random.randn(50)}
  23. plt.xlabel('entry a')
  24. plt.ylabel('entry b')
  25. plt.show()

plt.rcParams[]

pylot使用rc配置文件来自定义图形的各种默认属性,称之为rc配置或rc参数。通过rc参数可以修改默认的属性,包括窗体大小、每英寸的点数、线条宽度、颜色、样式、坐标轴、坐标和网络属性、文本、字体等。
rc参数存储在字典变量中,通过字典的方式进行访问,如下代码:

数据清洗

就是把数据从数值、格式等方面规范化。
python - 图4

  1. import pandas as pd
  2. import numpy as np
  3. ori_data = pd.read_excel('E:\\test.xlsx')
  4. data = pd.DataFrame(ori_data)
  5. data.head()
  6. colname = {'Unnamed: 0':'age'}
  7. data.rename(columns=colname, inplace=True)
  8. # .dropna():只要包含nan的行都删除
  9. newdata = data.dropna(axis=1,how='any') # 只有当一列中所有值都是NA时才删除该列
  10. newdata.loc['total']=newdata['total'].astype(np.float)
  11. pd.set_option('display.max_columns', 1000)
  12. pd.set_option('display.width', 1000)
  13. pd.set_option('display.max_colwidth', 1000)
  14. newdata=newdata.dropna(how='any') # delete the row(s) with nan
  15. print(newdata)
  1. #补全缺失值
  2. .fillna()
  3. 括号里可以是字典({column:value,...})或数字
  4. # 删除重复行:.drop_duplicates();制定子集:.drop_duplicates(['column'])

爬虫

网络数据获取

  1. import requests
  2. # 当爬取的网站有反爬虫机制时,要向服务器发出爬虫请求,需要添加请求头:headers
  3. #把user-agent换成自己电脑的user-agent。查找办法,在浏览器上输入about:version,
  4. #用户代理那一行显示的就是自己电脑的user-agent
  5. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)\ # \:换行符
  6. AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
  7. url = 'https://movie.douban.com/subject/33477335/comments/' # 要爬取数据的网址
  8. r=requests.get(url,headers=headers)
  9. print(r.status_code)
  10. #完整程序
  11. import requests
  12. from bs4 import BeautifulSoup
  13. import re # re正则表达式模块进行各类正则表达式处理
  14. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
  15. url = 'https://movie.douban.com/subject/33477335/comments/'
  16. r = requests.get(url, headers=headers)
  17. # 用beautifulsoup 传入字符串, 获得beautifulsoup对象soup
  18. soup = BeautifulSoup(r.text,'lxml')
  19. pattern = soup.find_all('span','short') #pattern是一个列表
  20. for item in pattern:
  21. print(item.string)
  22. pattern_s = re.compile('<span class="user-stars allstar(.*?) rating"')
  23. p = re.findall(pattern_s, r.text)
  24. s=0
  25. for star in p:
  26. s += int(star)
  27. print(s)

爬虫核心程序

  1. import requests
  2. import re
  3. headers={'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}
  4. def baidu(company):
  5. url='https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&ie=utf-8&word='+company
  6. res = requests.get(url, headers=headers).text
  7. # 提取超链接
  8. p_href = '<h3 class="news-title_1YtI1"><a href="(.*?)"'
  9. href=re.findall(p_href,res,re.S)
  10. # 提取题目
  11. p_title= '<h3 class="news-title_1YtI1">.*?>(.*?)</a>'
  12. title = re.findall(p_title,res,re.S)
  13. # 提取日期
  14. p_date = '<span class="c-color-gray2 c-font-normal">(.*?)</span>'
  15. date = re.findall(p_date,res)
  16. p_source = '<span class="c-color-gray c-font-normal c-gap-right">(.*?)</span>'
  17. source = re.findall(p_source,res)
  18. for i in range(len(title)):
  19. title[i]=title[i].strip() # strip()用来取消字符串两端的换行或空格
  20. title[i]=re.sub(r'<.*?>','',title[i])
  21. title[i] = re.sub(r'\u200b','',title[i])
  22. file = open(r'F:\数据挖掘报告.txt','a')
  23. file.write(str(company) + '\n')
  24. for i in range(len(title)):
  25. file.write(str(i+1)+'.'+title[i]+'('+date[i]+'-'+source[i]+')'+'\n')
  26. file.write(href[i]+'\n')
  27. file.write('--------------------'+'\n')
  28. company=['华为','阿里巴巴','美团','饿了吗']
  29. for i in company:
  30. baidu(i)

camelot:提取pdf里的表格

  1. import camelot
  2. tables = camelot.read_pdf('E:\\XXX\\文件名.pdf',flavor='stream',pages='6') # 一定要写flavor='stream'
  3. tables[0].df
  4. tables.export('XXX.xls',f='excel',compress = False)
  5. plt = camelot.plot(tables[0],kind='text')
  6. plt.show() #查看图表位置

用百度ai提取图片表格并转换为excel(推荐)

需要每次更换的是:request_id和access_token;
#client_id/secret的有效期是一个月左右
# encoding:utf-8
import requests
import base64
# step1:获取access_token
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = ‘https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=hTsFtKOkCgolR2eG1d68AHUT&client_secret=1W2EI6YhMeAYuk7eh0u1Z6ghBvXDNETE
response = requests.get(host)
if response:
print(response.json())
# ‘access_token’: ‘24.3282cb4d662b947c6e1d1e501f69fc31.2592000.1596958041.282335-21237240’
#step2:提交请求接口,获取request_id
request_url = “https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request
# 二进制方式打开图片文件
f = open(‘tabletest1.jpg’, ‘rb’)
img = base64.b64encode(f.read())
params = {“image”: img}
access_token = ‘24.3282cb4d662b947c6e1d1e501f69fc31.2592000.1596958041.282335-21237240’
request_url = request_url + “?access_token=” + access_token
headers = {‘content-type’: ‘application/x-www-form-urlencoded’}
response = requests.post(request_url, data=params, headers=headers)
# 若:response = requests.post(request_url, data=params, headers=headers,is_sync=True) 则同步返回同步返回识别结果,无需调用获取结果接口。
if response:
print (response.json())
# step3:获取结果
request_url = ‘https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result
params = {‘request_id’: ‘21237240_1953321’} # 每执行一次“提交请求接口”,request_id都会变
access_token = ‘24.3282cb4d662b947c6e1d1e501f69fc31.2592000.1596958041.282335-21237240’
request_url = request_url + “?access_token=” + access_token
headers={‘Content-Type’:’application/x-www-form-urlencoded’}
response = requests.post(request_url, data=params, headers=headers)
if response:
print (response.json())

post函数的请求参数

参数 是否必选 类型 可选值范围 说明
image string - 图像数据,base64编码后进行urlencode,要求base64编码和urlencode后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/jpeg/png/bmp格式
is_sync string true/false 是否同步返回识别结果。取值为“false”,需通过获取结果接口
获取识别结果;取值为“true”,同步返回识别结果,无需调用获取结果接口。默认取值为“false”
request_type string json/excel 当 is_sync=true 时,需在提交请求时即传入此参数指定获取结果的类型,取值为“excel”时返回xls文件的地址,取值为“json”时返回json格式的字符串。当 is_sync=false 时,需在获取结果时指定此参数。
  1. # encoding:utf-8
  2. import requests
  3. import base64
  4. # step1:获取access_token
  5. # client_id 为官网获取的AK, client_secret 为官网获取的SK
  6. host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=hTsFtKOkCgolR2eG1d68AHUT&client_secret=1W2EI6YhMeAYuk7eh0u1Z6ghBvXDNETE'
  7. response = requests.get(host)
  8. if response:
  9. print(response.json())
  10. # 提交请求接口
  11. # 'access_token': '24.3282cb4d662b947c6e1d1e501f69fc31.2592000.1596958041.282335-21237240'
  12. #step2:提交请求接口
  13. request_url = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request"
  14. # 二进制方式打开图片文件
  15. f = open('tabletest1.jpg', 'rb')
  16. img = base64.b64encode(f.read())
  17. params = {"image": img}
  18. access_token = '24.3282cb4d662b947c6e1d1e501f69fc31.2592000.1596958041.282335-21237240'
  19. request_url = request_url + "?access_token=" + access_token
  20. headers = {'content-type': 'application/x-www-form-urlencoded'}
  21. response = requests.post(request_url, data=params, headers=headers)
  22. if response:
  23. print (response.json())
  24. # 获取结果接口
  25. request_url = 'https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result'
  26. params = {'request_id': '21237240_1953321'} # 每执行一次“提交请求接口”,request_id都会变
  27. access_token = '24.3282cb4d662b947c6e1d1e501f69fc31.2592000.1596958041.282335-21237240'
  28. request_url = request_url + "?access_token=" + access_token
  29. headers={'Content-Type':'application/x-www-form-urlencoded'}
  30. response = requests.post(request_url, data=params, headers=headers)
  31. if response:
  32. print (response.json())

多层神经网络

  1. '''多层神经网络'''
  2. import numpy as np
  3. import scipy
  4. from scipy import ndimage
  5. import h5py
  6. import matplotlib.pyplot as plt
  7. import testCases #参见资料包,或者在文章底部copy
  8. from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward #参见资料包
  9. import lr_utils
  10. def initialize_parameters_deep(layers_dims):
  11. np.random.seed(3)
  12. parameters={}
  13. L= len(layers_dims)
  14. for i in range(1,L):
  15. parameters["W"+str(i)] = np.random.randn(layers_dims[i],layers_dims[i-1])/np.sqrt(layers_dims[i-1])
  16. parameters["b"+str(i)] = np.zeros((layers_dims[i],1))
  17. # 确保格式是正确的
  18. assert( parameters["W"+str(i)].shape == (layers_dims[i],layers_dims[i-1]))
  19. assert( parameters["b"+str(i)].shape == (layers_dims[i],1))
  20. return parameters
  21. def linear_forward(A,W,b):
  22. """
  23. 实现前向传播的线性部分。
  24. 参数:
  25. A - 来自上一层(或输入数据)的激活,维度为(上一层的节点数量,示例的数量)
  26. W - 权重矩阵,numpy数组,维度为(当前图层的节点数量,前一图层的节点数量)
  27. b - 偏向量,numpy向量,维度为(当前图层节点数量,1)
  28. 返回:
  29. Z - 激活功能的输入,也称为预激活参数
  30. cache - 一个包含“A”,“W”和“b”的字典,存储这些变量以有效地计算后向传递
  31. """
  32. Z = np.dot(W,A)+b
  33. assert(Z.shape == (W.shape[0],A.shape[1]))
  34. cache = (A,W,b)
  35. return Z,cache
  36. def linear_activation_forward(A_prev,W,b,activation):
  37. if activation == "sigmoid":
  38. Z,linear_cache = linear_forward(A_prev,W,b)
  39. A,activation_cache = sigmoid(Z)
  40. elif activation == "relu":
  41. Z, linear_cache = linear_forward(A_prev, W, b)
  42. A, activation_cache = relu(Z)
  43. assert (A.shape == (W.shape[0], A_prev.shape[1]))
  44. cache = (linear_cache, activation_cache)
  45. return A, cache
  46. def L_model_forward(X,parameters):
  47. '''参数:
  48. X - 数据,numpy数组,维度为(输入节点数量,示例数)
  49. parameters - initialize_parameters_deep()的输出
  50. 返回:
  51. AL - 最后的激活值
  52. caches - 包含以下内容的缓存列表:
  53. linear_relu_forward()的每个cache(有L-1个,索引为从0到L-2)
  54. linear_sigmoid_forward()的cache(只有一个,索引为L-1)
  55. '''
  56. caches = []
  57. A = X # X - 数据,numpy数组,维度为(输入节点数量,示例数)
  58. L = len(parameters) // 2 # 整除
  59. for l in range(1,L):
  60. A_prev = A
  61. A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], "relu")
  62. caches.append(cache)
  63. AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], "sigmoid")
  64. caches.append(cache)
  65. assert (AL.shape == (1, X.shape[1]))
  66. return AL, caches
  67. def compute_cost(AL, Y):
  68. """
  69. 实施等式(4)定义的成本函数。
  70. 参数:
  71. AL - 与标签预测相对应的概率向量,维度为(1,示例数量)
  72. Y - 标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量)
  73. 返回:
  74. cost - 交叉熵成本
  75. """
  76. m = Y.shape[1]
  77. # MA MB为matrix, multiply(MA, MB)对应元素相乘
  78. cost = -np.sum(np.multiply(np.log(AL), Y) + np.multiply(np.log(1 - AL), 1 - Y)) / m
  79. cost = np.squeeze(cost)
  80. assert (cost.shape == ())
  81. return cost
  82. def linear_backward(dZ, cache):
  83. """
  84. 为单层实现反向传播的线性部分(第L层)
  85. 参数:
  86. dZ - 相对于(当前第l层的)线性输出的成本梯度
  87. cache - 来自当前层前向传播的值的元组(A_prev,W,b)
  88. 返回:
  89. dA_prev - 相对于激活(前一层l-1)的成本梯度,与A_prev维度相同
  90. dW - 相对于W(当前层l)的成本梯度,与W的维度相同
  91. db - 相对于b(当前层l)的成本梯度,与b维度相同
  92. """
  93. A_prev, W, b = cache
  94. m = A_prev.shape[1]
  95. dW = np.dot(dZ, A_prev.T) / m
  96. db = np.sum(dZ, axis=1, keepdims=True) / m
  97. dA_prev = np.dot(W.T, dZ)
  98. assert (dA_prev.shape == A_prev.shape)
  99. assert (dW.shape == W.shape)
  100. assert (db.shape == b.shape)
  101. return dA_prev, dW, db
  102. def linear_activation_backward(dA, cache, activation="relu"):
  103. """
  104. 实现LINEAR-> ACTIVATION层的后向传播。
  105. 参数:
  106. dA - 当前层l的激活后的梯度值
  107. cache - 我们存储的用于有效计算反向传播的值的元组(值为linear_cache,activation_cache)
  108. activation - 要在此层中使用的激活函数名,字符串类型,【"sigmoid" | "relu"】
  109. 返回:
  110. dA_prev - 相对于激活(前一层l-1)的成本梯度值,与A_prev维度相同
  111. dW - 相对于W(当前层l)的成本梯度值,与W的维度相同
  112. db - 相对于b(当前层l)的成本梯度值,与b的维度相同
  113. """
  114. linear_cache, activation_cache = cache
  115. if activation == "relu":
  116. dZ = relu_backward(dA, activation_cache)
  117. dA_prev, dW, db = linear_backward(dZ, linear_cache)
  118. elif activation == "sigmoid":
  119. dZ = sigmoid_backward(dA, activation_cache)
  120. dA_prev, dW, db = linear_backward(dZ, linear_cache)
  121. return dA_prev, dW, db
  122. def L_model_backward(AL, Y, caches):
  123. """
  124. 对[LINEAR-> RELU] *(L-1) - > LINEAR - > SIGMOID组执行反向传播,就是多层网络的向后传播
  125. 参数:
  126. AL - 概率向量,正向传播的输出(L_model_forward())
  127. Y - 标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量)
  128. caches - 包含以下内容的cache列表:
  129. linear_activation_forward("relu")的cache,不包含输出层
  130. linear_activation_forward("sigmoid")的cache
  131. 返回:
  132. grads - 具有梯度值的字典
  133. grads [“dA”+ str(l)] = ...
  134. grads [“dW”+ str(l)] = ...
  135. grads [“db”+ str(l)] = ...
  136. """
  137. grads = {}
  138. L = len(caches)
  139. m = AL.shape[1]
  140. Y = Y.reshape(AL.shape)
  141. dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
  142. current_cache = caches[L - 1]
  143. grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache,
  144. "sigmoid")
  145. for l in reversed(range(L - 1)):
  146. current_cache = caches[l]
  147. dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, "relu")
  148. grads["dA" + str(l + 1)] = dA_prev_temp
  149. grads["dW" + str(l + 1)] = dW_temp
  150. grads["db" + str(l + 1)] = db_temp
  151. return grads
  152. def update_parameters(parameters, grads, learning_rate):
  153. """
  154. 使用梯度下降更新参数
  155. 参数:
  156. parameters - 包含你的参数的字典
  157. grads - 包含梯度值的字典,是L_model_backward的输出
  158. 返回:
  159. parameters - 包含更新参数的字典
  160. 参数[“W”+ str(l)] = ...
  161. 参数[“b”+ str(l)] = ...
  162. """
  163. L = len(parameters) // 2 # 整除
  164. for l in range(L):
  165. parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * grads["dW" + str(l + 1)]
  166. parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * grads["db" + str(l + 1)]
  167. return parameters
  168. def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False, isPlot=True):
  169. """
  170. 实现一个L层神经网络:[LINEAR-> RELU] *(L-1) - > LINEAR-> SIGMOID。
  171. 参数:
  172. X - 输入的数据,维度为(n_x,例子数)
  173. Y - 标签,向量,0为非猫,1为猫,维度为(1,数量)
  174. layers_dims - 层数的向量,维度为(n_y,n_h,···,n_h,n_y)
  175. learning_rate - 学习率
  176. num_iterations - 迭代的次数
  177. print_cost - 是否打印成本值,每100次打印一次
  178. isPlot - 是否绘制出误差值的图谱
  179. 返回:
  180. parameters - 模型学习的参数。 然后他们可以用来预测。
  181. """
  182. np.random.seed(1)
  183. costs = []
  184. parameters = initialize_parameters_deep(layers_dims)
  185. for i in range(0, num_iterations):
  186. AL, caches = L_model_forward(X, parameters)
  187. cost = compute_cost(AL, Y)
  188. grads = L_model_backward(AL, Y, caches)
  189. parameters = update_parameters(parameters, grads, learning_rate)
  190. # 打印成本值,如果print_cost=False则忽略
  191. if i % 100 == 0:
  192. # 记录成本
  193. costs.append(cost)
  194. # 是否打印成本值
  195. if print_cost:
  196. print("第", i, "次迭代,成本值为:", np.squeeze(cost))
  197. # 迭代完成,根据条件绘制图
  198. if isPlot:
  199. plt.plot(np.squeeze(costs))
  200. plt.ylabel('cost')
  201. plt.xlabel('iterations (per tens)')
  202. plt.title("Learning rate =" + str(learning_rate))
  203. plt.show()
  204. return parameters
  205. train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = lr_utils.load_dataset()
  206. train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
  207. test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
  208. train_x = train_x_flatten / 255
  209. train_y = train_set_y
  210. test_x = test_x_flatten / 255
  211. test_y = test_set_y
  212. layers_dims = [12288, 20, 7, 5, 1] # 5-layer model
  213. parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True,isPlot=True)
  214. def predict(X, y, parameters):
  215. """
  216. 该函数用于预测L层神经网络的结果,当然也包含两层
  217. 参数:
  218. X - 测试集
  219. y - 标签
  220. parameters - 训练模型的参数
  221. 返回:
  222. p - 给定数据集X的预测
  223. """
  224. m = X.shape[1]
  225. n = len(parameters) // 2 # 神经网络的层数
  226. p = np.zeros((1, m))
  227. # 根据参数前向传播
  228. probas, caches = L_model_forward(X, parameters)
  229. for i in range(0, probas.shape[1]):
  230. if probas[0, i] > 0.5:
  231. p[0, i] = 1
  232. else:
  233. p[0, i] = 0
  234. print("准确度为: " + str(float(np.sum((p == y)) / m)))
  235. return p
  236. pred_train = predict(train_x, train_y, parameters) #训练集
  237. pred_test = predict(test_x, test_y, parameters) #测试集
  238. ## START CODE HERE ##
  239. my_image = "my_image.jpg" # change this to the name of your image file
  240. my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
  241. ## END CODE HERE ##
  242. #输入自己的照片去预测
  243. fname = "images/" + my_image
  244. image = np.array(ndimage.imread(fname, flatten=False))
  245. my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))
  246. my_predicted_image = predict(my_image, my_label_y, parameters)
  247. plt.imshow(image)
  248. print ("y = " + str(np.squeeze(my_predicted_image)) + ", your L-layer model predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")

预测鲍鱼年龄

  1. '''预测鲍鱼年龄'''
  2. import pandas as pd
  3. # load data
  4. data = pd.read_csv("C:\\Users\\as\\PycharmProjects\\untitled\\abalone.data", header=None)
  5. data.columns = ['Sex', 'Length', 'Diameter', 'Height', 'Whole-weight', 'Shucked-weight', 'Viscera-weight', 'Shell-weight', 'Rings']
  6. # preprocess data
  7. print(data.head())

image.png

  1. '''预测鲍鱼年龄
  2. Sex / nominal / -- / M, F, and I (infant)
  3. Length / continuous / mm / Longest shell measurement
  4. Diameter / continuous / mm / perpendicular to length
  5. Height / continuous / mm / with meat in shell
  6. Whole weight / continuous / grams / whole abalone
  7. Shucked weight / continuous / grams / weight of meat
  8. Viscera weight / continuous / grams / gut weight (after bleeding)
  9. Shell weight / continuous / grams / after being dried
  10. Rings / integer / -- / +1.5 gives the age in years
  11. '''
  12. import pandas as pd
  13. import numpy as np
  14. import matplotlib.pyplot as plt
  15. # load data
  16. data = pd.read_csv("C:\\Users\\as\\PycharmProjects\\untitled\\abalone.data", header=None)
  17. data.columns = ['Sex', 'Length', 'Diameter', 'Height', 'Whole_weight', 'Shucked_weight', 'Viscera_weight', 'Shell_weight', 'Rings']
  18. # preprocess data
  19. # 对性别进行数值化
  20. for i in range(0,data['Sex'].shape[0]):
  21. if data.loc[i,'Sex'] == 'M':
  22. data.loc[i,'Sex'] = 3 # 赋值时应使用DataFrame.loc[行名][列名]
  23. elif data.loc[i,'Sex'] == 'F':
  24. data.loc[i,'Sex'] =2
  25. else:
  26. data.loc[i,'Sex'] = 1
  27. x = data.drop('Rings', axis=1)
  28. y = data['Rings'] + 1.5
  29. def standRegress(xArr,yArr):
  30. '''
  31. 函数说明:计算回归系数
  32. xArr-x数据集
  33. yArr-y数据集
  34. ws-回归系数
  35. '''
  36. xMat = np.mat(x) # np.mat生成数组
  37. yMat = np.mat(y).T
  38. xTx = xMat.T * xMat # 矩阵乘积np.dot()
  39. if np.linalg.det(xTx) == 0.0:
  40. print("矩阵为奇异矩阵,不能求逆")
  41. return
  42. ws = xTx.I * (xMat.T*yMat)
  43. return ws
  44. def Regression():
  45. ws = standRegress(x,y)
  46. xMat = np.mat(x)
  47. yMat = np.mat(y)
  48. xCopy = xMat.copy()
  49. xCopy.sort(0)
  50. yhat = xCopy*ws
  51. fig = plt.figure()
  52. ax = fig.add_subplot(111)
  53. ax.plot(xCopy[:,3], yhat,c='red')
  54. ax.scatter(xMat[:, 3].flatten().A[0], yMat.flatten().A[0], s=20, c='blue', alpha=.5) # 绘制样本点
  55. plt.title('DataSet') # 绘制title
  56. plt.xlabel('X')
  57. plt.show()
  58. if __name__ == '__main__':
  59. Regression()

初始化参数:

1.1:使用0来初始化参数。
1.2:使用随机数来初始化参数。
1.3:使用抑梯度异常初始化参数(参见视频中的梯度消失和梯度爆炸)。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import sklearn
  4. import sklearn.datasets
  5. import init_utils # 第一部分,初始化
  6. import reg_utils # 第二部分,正则化
  7. import gc_utils # 第三部分,梯度校验
  8. plt.rcParams['figure.figsize'] = (7.0,4.0)
  9. plt.rcParams['image.interpolation'] = 'nearest'
  10. train_X, train_Y, test_X, test_Y = init_utils.load_dataset(is_plot=True)
  11. plt.show()
  12. def initialize_parameters_zeros(layers_dims):
  13. parameters={}
  14. L=len(layers_dims)
  15. for l in range(1,L):
  16. parameters['W'+str(l)] = np.zeros(layers_dims[l], layers_dims[l - 1])
  17. parameters['b'+str(l)] = np.zeros(layers_dims[l],1)
  18. return parameters
  19. def initialize_parameters_random(layers_dims):
  20. np.random.seed(3)
  21. parameters = {}
  22. L = len(layers_dims)
  23. for l in range(1, L):
  24. parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1])*10
  25. parameters['b' + str(l)] = np.random.randn(layers_dims[l], 1)
  26. return parameters
  27. def initialize_parameters_he(layers_dims):
  28. np.random.seed(3)
  29. parameters = {}
  30. L = len(layers_dims)
  31. for l in range(1, L):
  32. parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) * np.sqrt(2/layers_dims[l-1])
  33. parameters['b' + str(l)] = np.random.randn(layers_dims[l], 1)
  34. return parameters
  35. def model(X,Y,learning_rate=0.01,num_iterations=15000,print_cost=True,initialization='he',is_polt=True):
  36. '''
  37. neutral network with 3 layers
  38. '''
  39. grads = {}
  40. costs = []
  41. m = X.shape[1]
  42. layer_dims = [X.shape[0],10,5,1]
  43. if initialization == "zeros":
  44. parameters = initialize_parameters_zeros(layer_dims)
  45. elif initialization == 'random':
  46. parameters = initialize_parameters_random(layer_dims)
  47. elif initialization == 'he':
  48. parameters = initialize_parameters_he(layer_dims)
  49. else :
  50. print("输入了错误的参数")
  51. exit()
  52. # start learning
  53. for i in range(0,num_iterations):
  54. # 前向传播
  55. a3, cache = init_utils.forward_propagation(X, parameters)
  56. # 计算成本
  57. cost = init_utils.compute_loss(a3, Y)
  58. # 反向传播
  59. grads = init_utils.backward_propagation(X, Y, cache)
  60. # 更新参数
  61. parameters = init_utils.update_parameters(parameters, grads, learning_rate)
  62. # 记录成本
  63. if i % 1000 == 0:
  64. costs.append(cost)
  65. # 打印成本
  66. if print_cost:
  67. print("第" + str(i) + "次迭代,成本值为:" + str(cost))
  68. if is_polt:
  69. plt.plot(costs)
  70. plt.ylabel('cost')
  71. plt.xlabel('iterations')
  72. plt.title("Learning rate =" + str(learning_rate))
  73. plt.show()
  74. return parameters
  75. parameters = model(train_X, train_Y, initialization = "he",is_polt=True)
  76. print("训练集:")
  77. predictions_train = init_utils.predict(train_X, train_Y, parameters)
  78. print("测试集:")
  79. predictions_test = init_utils.predict(test_X, test_Y, parameters)
  80. print(predictions_train)
  81. print(predictions_test)
  82. plt.title("Model with large random initialization")
  83. axes = plt.gca()
  84. axes.set_xlim([-1.5, 1.5])
  85. axes.set_ylim([-1.5, 1.5])
  86. init_utils.plot_decision_boundary(lambda x: init_utils.predict_dec(parameters, x.T), train_X, train_Y)