关于Python数据抓取、分析、挖掘、机器学习和Python分布式计算内容分享

开发 后端 机器学习 分布式
本文主要是关于 Python 数据抓取、分析、挖掘、机器学习和Python 分布式计算内容的分享。

关于Python数据抓取、分析、挖掘、机器学习和Python分布式计算内容分享

01 数据抓取

1、背景调研

1)检查robots.txt,了解爬取该网站有哪些限制;

2)pip install builtwith;pip install python-whois

2、数据抓取:

1)动态加载的内容:

使用selenium

 

  1. #!/usr/bin/env python 
  2. # -*- coding: utf-8 -*- 
  3. from selenium import webdriver 
  4. from selenium.webdriver.common.keys import Keys 
  5. import time 
  6. import sys 
  7. reload(sys) 
  8. sys.setdefaultencoding('utf8'
  9. driver = webdriver.Chrome("/Users/didi/Downloads/chromedriver") driver.get('http://xxx'
  10. elem_account = driver.find_element_by_name("UserName"
  11. elem_password = driver.find_element_by_name("Password"
  12. elem_code = driver.find_element_by_name("VerificationCode") elem_account.clear() 
  13. elem_password.clear() 
  14. elem_code.clear() 
  15. elem_account.send_keys("username"
  16. elem_password.send_keys("pass"
  17. elem_code.send_keys("abcd"
  18. time.sleep(10) 
  19. driver.find_element_by_id("btnSubmit").submit() 
  20. time.sleep(5) driver.find_element_by_class_name("txtKeyword").send_keys(u"x") #模拟搜索 driver.find_element_by_class_name("btnSerch").click() 
  21. # ...省略处理过程 
  22. dw = driver.find_elements_by_xpath('//li[@class="min"]/dl/dt/a'
  23. for item in dw: 
  24. url = item.get_attribute('href'
  25.    if url: 
  26.  ulist.append(url) 
  27.  print(url + "---" + str(pnum)) 
  28.  print("##################"

2)静态加载的内容

(1)正则;

(2)lxml;

(3)bs4

 

  1. #!/usr/bin/env python 
  2. # -*- coding: utf-8 -*- 
  3. string = r'src="(http://imgsrc\.baidu\.com.+?\.jpg)" pic_ext="jpeg"' # 正则表达式字符串 urls = re.findall(string, html) 
  4. import requests 
  5. from lxml import etree 
  6. import urllib 
  7. response = requests.get(url) 
  8. html = etree.HTML(requests.get(url).content) 
  9. res = html.xpath('//div[@class="d_post_content j_d_post_content "]/img[@class="BDE_Image"]/@src') # lxml 
  10. import requests 
  11. from bs4 import BeautifulSoup 
  12. soup = BeautifulSoup(response.text, 'lxml') # 解析response并创建BeautifulSoup对象 urls = soup.find_all('img''BDE_Image'

3):反爬与反反爬

(1):请求频率;

(2):请求头;

(3):IP代理;

4):爬虫框架:

(1):Scrapy

(2):Portia

02 数据分析

1、常用的数据分析库:

NumPy:是基于向量化的运算。http://www.numpy.org/

1)List => 矩阵

2)ndim:维度;shape:行数和列数;size:元素个数

Scipy:是NumPy的扩展,有高等数学、信号处理、统计等。https://www.scipy.org/

Pandas:是基于NumPy的快速构建高级数据结构的包,数据结构:Series和DataFrame。http://pandas.pydata.org/

1):NumPy类似于List,Pandas 类似于Dict。

Matplotlib:绘图库。

1):是一个强大的绘图工具;

2):支持散点图、线图、柱状图等;

简单例子: 

  1. pip2 install Numpy 
  2. >>> import numpy as np 
  3. >>> a = np.arange(10) 
  4. >>> a 
  5. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 
  6. >>> a ** 2 
  7. array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81]) 
  8. pip2 install Scipy 
  9. >>> import numpy as np 
  10. >>> from scipy import linalg 
  11. >>> a = np.array([[1, 2], [3, 4]]) 
  12. >>> linalg.det(a) 
  13. -2.0 
  14. pip2 install pandas 
  15. >>> df = pd.DataFrame({ 'A' : pd.date_range("20170802", periods=5), 'B' : pd.Series([11, 22, 33, 44, 
  16. 55]), 'C' : pd.Categorical(["t","a","b","c","g"])}) 
  17. >>> df 
  18. ABC 0 2017-08-02 11 t 1 2017-08-03 22 a 2 2017-08-04 33 b 3 2017-08-05 44 c 4 2017-08-06 55 g 
  19. pip2 install Matplotlib 
  20. >>> import matplotlib.pyplot as plt 
  21. >>> plt.plot([1, 2, 3]) 
  22. [<matplotlib.lines.Line2D object at 0x113f88f50>] 
  23. >>> plt.ylabel("didi"
  24. <matplotlib.text.Text object at 0x110b21c10> 
  25. >>> plt.show() 

2、高级数据分析库: 

scikit-learn:机器学习框架。

 

图上可以表示出数据小于50,No:需要更多的数据, Yes使用分类器,一直走下去;

由图中,可以看到算法有四类,分类,回归,聚类,降维。

 KNN: 

  1. #!/usr/local/bin/python 
  2. # -*- coding: utf-8 -*- 
  3. ''
  4. 预测Iris https://en.wikipedia.org/wiki/Iris_flower_data_set ''
  5. # 导入模块 
  6. from __future__ import print_function 
  7. from sklearn import datasets 
  8. from sklearn.model_selection import train_test_split 
  9. from sklearn.neighbors import KNeighborsClassifier 
  10. # 创建数据 
  11. iris = datasets.load_iris() 
  12. iris_X = iris.data # 花萼的长宽、 花瓣的长宽 
  13. iris_y = iris.target # 花的种类 0, 1, 2 
  14. print(iris_X) 
  15. print(iris_y) 
  16. print(iris.target_names) 
  17. # 定义模型-训练模型-预测 
  18. X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size = 0.1) # 训练数据10% knn = KNeighborsClassifier() # 创建KNN近邻器 
  19. knn.fit(X_train, y_train) # 训练数据 
  20. predicts = knn.predict(X_test) # 得到预测结果 
  21. # 对比结果 
  22. print("#########################"
  23. print(X_test) 
  24. print(predicts) 
  25. print(y_test) 
  26. # 计算预测准确率 
  27. print(knn.score(X_test, y_test)) 
  28. [[ 5.   3.3  1.4  0.2] 
  29. [ 5.   3.5  1.3  0.3] 
  30. [ 6.7  3.1  5.6  2.4] 
  31. [ 5.8  2.7  3.9  1.2] 
  32. [ 6.   2.2  5.   1.5] 
  33. [ 6.   3.   4.8  1.8] 
  34. [ 6.3  2.5  5.   1.9] 
  35. [ 5.   3.6  1.4  0.2] 
  36. [ 5.6  2.9  3.6  1.3] 
  37. [ 6.9  3.2  5.7  2.3] 
  38. [ 4.9  3.   1.4  0.2] 
  39. [ 5.9  3.   4.2  1.5] 
  40. [ 4.8  3.   1.4  0.1] 
  41. [ 5.1  3.4  1.5  0.2] 
  42. [ 4.7  3.2  1.6  0.2]] 
  43. [0 0 2 1 1 2 2 0 1 2 0 1 0 0 0] 
  44. [0 0 2 1 2 2 2 0 1 2 0 1 0 0 0] 
  45. 0.933333333333  

Linear Regression 

  1. #!/usr/local/bin/python # -*- coding: utf-8 -*- ''
  2. 波士顿房价趋势 
  3. ''
  4. # 导入模块 
  5. from __future__ import print_function 
  6. from sklearn import datasets 
  7. from sklearn.linear_model import LinearRegression 
  8. import matplotlib.pyplot as plt 
  9. # 创建数据 
  10. loaded_data = datasets.load_boston() #波士顿的房价 
  11. data_X = loaded_data.data 
  12. data_y = loaded_data.target 
  13. print(data_X) 
  14. print(data_y) 
  15. # 定义模型-训练模型-预测 
  16. model = LinearRegression() # 线性回归 
  17. model.fit(data_X, data_y) # 训练数据 
  18. print(model.predict(data_X[:4, :])) # 得到预测结果 
  19. print(data_y[:4]) 
  20. # 结果 
  21. print("#########################"
  22. X, y = datasets.make_regression(n_samples=100, n_features=1, noise=10) # 生成回归模型数据100个样本, 每个样本一个特征, 高斯噪声 
  23. plt.scatter(X, y) # 散点图 
  24. plt.show() 

 

03 数据挖掘

1、挖掘关键词:

涉及到的算法:TF-IDF

参考文献:http://www.ruanyifeng.com/blog/2013/03/tf-idf.html

news.txt:

滴滴出行与欧非地区领先出行企业Taxify达成战略合作 支持跨地区交通技术创新

2017-08-01 滴滴出行 【2017年8月1日,中国,北京/爱沙尼亚,塔林】滴滴出行今日宣布与欧非地区移动出行领军企业Taxify达成战略合作 。滴滴将通过投资以及智能交通技术研发等方面协作,支持Taxify在多元市场进行更深度的市场拓展和技术创新。 滴滴出行是全球领先的移动出行平台。依靠人工智能技术, 滴滴在超过400个城市为4亿多用户提供包括出租车、专车、快车、豪华车和顺风车等在内的多元化出行服务。在为1700 余万司机提供灵活就业与收入机会的同时,滴滴也以人工智能技术支持城市管理者建设一体化、可持续的智慧交通解决 方案。 Taxify于2013年成立于爱沙尼亚,是欧洲和非洲地区成长最快的移动出行企业。目前其出租车和私家车共享出行服务网 络遍及欧洲、非洲、西亚的中心城市;触达匈牙利、罗马尼亚、波兰、波罗的海三国、南非、尼日利亚、肯尼亚等18个 国家,拥有超过250万用户。 滴滴出行创始人、CEO程维表示:“Taxify在多元化的市场提供优质的创新型出行服务。我们都致力于运用移动互联网 科技的力量,满足迅速演变的消费者需求;帮助传统交通行业转型升级。我相信这一合作将为亚洲,欧洲和非洲市场间 构建跨地区智慧交通纽带作出贡献。”

Taxify创始人、CEO马克斯·维利格(Marcus Villig)表示:“Taxify将借力此次战略合作,巩固我们在欧洲和非洲核心市场的优势地位。我们相信滴滴是最理想的 伙伴,能帮助我们成为欧非地区***和最有效率的出行选择。” 

  1. #!/usr/local/bin/python # -*- coding: utf-8 -*- ''
  2. 分析文章关键词 
  3. ''
  4. import os 
  5. import codecs 
  6. import pandas 
  7. import jieba 
  8. import jieba.analyse 
  9. # 格式化数据格式 
  10. tagDF = pandas.DataFrame(columns=['filePath''content''tag1''tag2''tag3''tag4''tag5']) try: 
  11. with open('./houhuiyang/news.txt''r'as f: #载入语料库 content = f.read().strip() 
  12.    tags = jieba.analyse.extract_tags(content, topK=5) #TF_IDF 
  13.    tagDF.loc[len(tagDF)] = ["./news.txt", content, tags[0], tags[1], tags[2], tags[3], tags[4]] 
  14.    print(tagDF) 
  15. except Exception, ex: 
  16.    print(ex) 

 

计算出文章Top5的关键词:出行、滴滴、Taxify、欧非、交通

2、情感分析

情感用语资料:http://www.keenage.com/html/c_bulletin_2007.htm 

1)最简单的方式就是基于情感词典的方法; 

2)复杂的就是基于机器学习的方法; 

  1. pip2 install nltk 
  2.  
  3. >>> import nltk 
  4.  
  5. >>> from nltk.corpus import stopwords #停止词 >>> nltk.download() # 安装语料库 
  6.  
  7. >>> t = "Didi is a travel company" 
  8.  
  9. >>> word_list = nltk.word_tokenize(t) 
  10.  
  11. >>> filtered_words = [word for word in word_list if word not in stopwords.words('english')] ['Didi''travel''company'
  12.  
  13. >>> nltk.download('stopwords') #下载停止词  

中英文NLP分词区别

1):启发式 Heuristic

2):机器学习/统计法:HMM、CRF

处理流程:raw_text -> tokenize[pos tag] -> lemma / stemming[pos tag] -> stopwords -> word_list

04 Python 分布式计算 

  1. pip2 install mrjjob 
  2.  
  3. pip2 install pyspark  

1)Python 多线程;

2)Python 多进程【multiprocessing】; 

3)全局解释器锁GIL; 

4)进程间通信Queue;

5)进程池Pool;

6)Python的高阶函数; 

  1. map/reduce/filter 

7)基于Linux的管道的MapReducer 【cat word.log | python mapper.py | python reducer.py | sort -k 2r】

word.log

北京 成都 上海 北京 山西 天津 广州 

  1. #!/usr/local/bin/python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5. ''
  6.  
  7. mapper 
  8.  
  9. ''
  10.  
  11. import sys 
  12.  
  13. try: 
  14.  
  15.    for lines in sys.stdin: 
  16.  
  17.        line = lines.split() 
  18.  
  19.        for word in line: 
  20.  
  21.            if len(word.strip()) == 0: 
  22.  
  23.                continue 
  24.  
  25.            count = "%s,%d" % (word, 1) 
  26.  
  27.            print(count
  28.  
  29. except IOError, ex: 
  30.  
  31. print(ex) 
  32.  
  33. #!/usr/local/bin/python 
  34.  
  35. # -*- coding: utf-8 -*- 
  36.  
  37. ''
  38.  
  39. reducer 
  40.  
  41. ''
  42.  
  43. import sys 
  44.  
  45. try: 
  46.  
  47.    word_dict = {} 
  48.  
  49.    for lines in sys.stdin: 
  50.  
  51.        line = lines.split(","
  52.  
  53.        if len(line) != 2: 
  54.  
  55.            continue 
  56.  
  57.        word_dict.setdefault(line[0], 0) 
  58.  
  59.        word_dict[line[0]] += int(line[1]) 
  60.  
  61.    for key, val in word_dict.items(): 
  62.  
  63.     stat = "%s %d" % (key, val) 
  64.  
  65.        print(stat) 
  66.  
  67. except IOError, ex: 
  68.  
  69. print(ex) 

05 神经网络

分别有CPU/GPU版本

1)tensorflow 建立的神经网络是静态的

2)pytorch http://pytorch.org/#pip-install-pytorch 建立的神经网络是动态的 【Troch 是Lua写的,这个是Python版本】

简单说数据:

 

标量(Scalar)是只有大小,没有方向的量,如1,2,3等

向量(Vector)是有大小和方向的量,其实就是一串数字,如(1,2) 

矩阵(Matrix)是好几个向量拍成一排合并而成的一堆数字,如[1,2;3,4] 

张量(Tensor)是按照任意维排列的一堆数字的推广。如图所示,矩阵不过是三维张量下的一个二维切面。要找到三维张量下的一个 标量,需要三个维度的坐标来定位。

TensorFlow pytorch用张量这种数据结构来表示所有的数据。 

  1. #-*- coding: UTF-8 -*- 
  2. #author houhuiyang 
  3. import torch 
  4. import numpy as np 
  5. from torch.autograd import Variable 
  6. import torch.nn.functional as F 
  7. import matplotlib.pyplot as plt 
  8. np_data = np.arange(6).reshape((2, 3)) 
  9. torch_data = torch.from_numpy(np_data) 
  10. tensor2np = torch_data.numpy() 
  11. print( 
  12. "\nnp_data", np_data, #矩阵 
  13. "\ntorch_data", torch_data, #张量 
  14.   "\ntensor to numpy", tensor2np 
  15. # data = [-1, -2, 1, 2, 3] 
  16. data = [[1, 2], [3, 4]] 
  17. tensor = torch.FloatTensor(data) 
  18. abs sin cos mean平均值 matmul/mm print( 
  19.   "\nnumpy", np.matmul(data, data), 
  20.   "\ntorch", torch.mm(tensor, tensor) 
  21. # tensor variable 
  22. tensor_v = torch.FloatTensor([[1,2], [3,4]]) variable = Variable(tensor_v, requires_grad=True) # 计算中值 
  23. t_out = torch.mean(tensor_v * tensor_v) # x ^ 2 v_out = torch.mean(variable * variable) # 反向传播 print( 
  24.   tensor_v, 
  25.   variable, 
  26.   t_out, 
  27.   v_out 
  28. v_out.backward() # 反向传递 
  29. print(variable.grad) # 梯度 
  30. ''
  31. y = Wx 线性 
  32. y =AF(Wx)非线性 【激励函数 relu/sigmoid/tanh】 
  33. ''
  34. x =torch.linspace(-5,5,200) # 从-5到5取200个点 
  35. x = Variable(x) 
  36. x_np = x.data.numpy() 
  37. y_relu = F.relu(x).data.numpy() 
  38. y_sigmoid = F.sigmoid(x).data.numpy() 
  39. y_tanh = F.tanh(x).data.numpy() 
  40. # y_softplus = F.softplus(x).data.numpy() # 概率图 plt.figure(1, figsize=(8, 6)) 
  41. # plt.subplot(221) # 绘制子图 
  42. plt.plot(x_np, y_relu, c = "red", label = "relu") plt.ylim(-1, 5) 
  43. plt.legend(loc = "best"
  44. plt.show() 
  45. # plt.subplot(222) 
  46. plt.plot(x_np, y_sigmoid, c = "red", label = "igmoid"
  47. plt.ylim(-0.2, 1.2) 
  48. plt.legend(loc = "best"
  49. plt.show() 
  50. # plt.subplot(223) 
  51. plt.plot(x_np, y_tanh, c = "red", label = "subplot"
  52. plt.ylim(-1.2, 1.2) 
  53. plt.legend(loc = "best"
  54. plt.show() 

搭建简单的神经网络 

  1. #-*- coding: UTF-8 -*- #author 守望之心 
  2. ''
  3. 回归 
  4. 分类 
  5. ''
  6. import torch 
  7. from torch.autograd import Variable 
  8. import torch.nn.functional as F # 激励函数 
  9. import matplotlib.pyplot as plt 
  10. x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim = 1) # unsqueeze 一维转变为二维 y = x.pow(2) + 0.2 * torch.rand(x.size()) 
  11. x, y = Variable(x), Variable(y) 
  12. # print(x) 
  13. # print(y) 
  14. # plt.scatter(x.data.numpy(), y.data.numpy()) 
  15. # plt.show() 
  16. class Net(torch.nn.Module): # 继承 torch 的Moudle 
  17. def __init__(self, n_features, n_hidden, n_output): 
  18. super(Net, self).__init__() # 继承torch __init__ 
  19. self.hidden = torch.nn.Linear(n_features, n_hidden) # 隐藏层线性输出 self.predict = torch.nn.Linear(n_hidden, n_output) # 输出线性层 
  20. def forward(self, x): 
  21. x = F.relu(self.hidden(x)) # 激励函数 x = self.predict(x) # 输出值 
  22. return x 
  23. net = Net(1, 10, 1) # 输入值, 隐藏层10,10个神经元, 1个输出值 print(net) # 输出搭建的神经网络结构 
  24. plt.ion() 
  25. plt.show() 
  26. # 训练工具 
  27. optimizer = torch.optim.SGD(net.parameters(), lr = 0.5) # 传入net的所有值, lr是学习率 loss_func = torch.nn.MSELoss() # 均方差 
  28. print(net.parameters()) 
  29. for t in range(100): 
  30. prediction = net(x) #喂给net 训练数据x, 输出预测值 loss = loss_func(prediction, y) # 计算两者误差 
  31. # 反向传播 
  32. optimizer.zero_grad() 
  33. loss.backward() 
  34. optimizer.step() 
  35. if t % 5 == 0: 
  36.  plt.cla() 
  37.  plt.scatter(x.data.numpy(), y.data.numpy()) 
  38.  plt.plot(x.data.numpy(), prediction.data.numpy(), "r-", lw = 5) 
  39.  plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 20, 'color':  'red'}) 
  40.  plt.pause(0.1) 
  41. plt.ioff() 
  42. plt.show() 

06 数学 微积分

1、极限: 

无穷大无穷小阶数;

2、微分学: 

导数:

1)导数就是曲线的斜率,是曲线变化快慢的反应;

2)二阶导数是斜率变化快慢的反应,表现曲线的凸凹性; 

泰勒级数逼近

牛顿法和梯度下降; 

3、Jensen不等式:

凸函数;Jensen不等式

概率论:

1、积分学: 

牛顿-莱布尼茨公式

2、概率空间

随机变量与概率:概率密度函数的积分;条件概率;共轭分布;

概率分布: 

1)两点分布/贝努力分布;

2)二项分布; 

3)泊松分布; 

4)均匀分布; 

5)指数分布; 

6)正态分布/高斯分布;

3、大数定律和中心极限

线性代数:

1)矩阵 

2)线性回归; 

责任编辑:庞桂玉 来源: 程序人生
相关推荐

2017-04-25 15:40:12

数据分析商品评价

2021-09-09 15:45:17

机器学习人工智能Ray

2023-11-01 18:02:33

RayPython分布式

2010-03-03 15:39:50

Python抓取网页内

2024-03-01 09:53:34

2015-06-10 09:47:18

微软分布式云平台

2016-08-31 07:02:51

2017-09-01 05:35:58

分布式计算存储

2019-11-21 14:01:37

Python数据挖掘机器学习

2018-04-23 11:11:52

数据挖掘机器学习Python

2021-07-23 08:57:32

鸿蒙HarmonyOS应用

2018-11-07 09:23:21

服务器分布式机器学习

2021-12-28 17:03:29

数据质量分布式

2015-09-23 14:32:30

NFV分布式数据环境

2017-12-05 14:55:56

2022-08-03 20:18:58

机器学习算法分析数据

2013-03-26 13:43:08

Java分布式计算

2012-09-19 14:09:20

Hadoop开源

2017-06-29 13:29:34

大数据PAI机器学习

2013-10-16 11:36:08

分布式大数据
点赞
收藏

51CTO技术栈公众号