成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

關于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

2024-03-01 09:53:34

2017-09-01 05:35:58

分布式計算存儲

2016-08-31 07:02:51

2015-06-10 09:47:18

微軟分布式云平臺

2021-07-23 08:57:32

鴻蒙HarmonyOS應用

2023-11-01 18:02:33

RayPython分布式

2018-11-07 09:23:21

服務器分布式機器學習

2021-12-28 17:03:29

數據質量分布式

2015-09-23 14:32:30

NFV分布式數據環境

2018-04-23 11:11:52

數據挖掘機器學習Python

2019-11-21 14:01:37

Python數據挖掘機器學習

2010-03-03 15:39:50

Python抓取網頁內

2012-09-19 14:09:20

Hadoop開源

2013-03-26 13:43:08

Java分布式計算

2017-12-05 14:55:56

2022-08-03 20:18:58

機器學習算法分析數據

2017-06-29 13:29:34

大數據PAI機器學習

2023-01-13 07:39:07

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 四虎永久在线精品免费一区二 | 日韩视频在线免费观看 | 成人欧美一区二区三区黑人孕妇 | 中文字幕在线播放第一页 | 日日干天天操 | 天天操欧美 | 中文字幕av第一页 | 国产欧美日韩综合精品一 | 91爱爱·com | 亚洲精品色 | 91视频网址| 野狼在线社区2017入口 | 亚洲欧美一区二区三区视频 | 国产欧美久久精品 | 日韩欧美一级片 | 91社区在线观看播放 | 亚洲一区二区三区四区五区午夜 | 黄色网址免费看 | 国产高清一区二区三区 | 欧美综合在线观看 | 亚洲激情综合 | 全部免费毛片在线播放网站 | 国产精品美女久久久久久久久久久 | 久久久高清 | 久久成人一区 | 超碰在线97国产 | 黄色a三级| 婷婷久久一区 | 欧美日韩中文字幕 | 日韩国产欧美在线观看 | 精品一区二区三区免费视频 | 在线观看av网站 | 日韩一区二区三区在线视频 | 污污免费网站 | 国产成人精品免费视频大全最热 | 伊人色综合久久天天五月婷 | 日本亚洲欧美 | 国产精品入口麻豆www | 天天干视频 | 欧美a在线 | 欧美一级大片免费看 |