内容简介:关于Python数据抓取、分析、挖掘、机器学习和Python分布式计算内容分享
01 数据抓取
1、背景调研
1)检查robots.txt,了解爬取该网站有哪些限制;
2)pip install builtwith;pip install python-whois
2、数据抓取:
1)动态加载的内容:
使用selenium
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import sys
reload(sys)
sys.setdefaultencoding('utf8')
driver = webdriver.Chrome("/Users/didi/Downloads/chromedriver") driver.get('http://xxx')
elem_account = driver.find_element_by_name("UserName")
elem_password = driver.find_element_by_name("Password")
elem_code = driver.find_element_by_name("VerificationCode") elem_account.clear()
elem_password.clear()
elem_code.clear()
elem_account.send_keys("username")
elem_password.send_keys("pass")
elem_code.send_keys("abcd")
time.sleep(10)
driver.find_element_by_id("btnSubmit").submit()
time.sleep(5) driver.find_element_by_class_name("txtKeyword").send_keys(u"x") #模拟搜索 driver.find_element_by_class_name("btnSerch").click()
# ...省略处理过程
dw = driver.find_elements_by_xpath('//li[@class="min"]/dl/dt/a')
for item in dw:
url = item.get_attribute('href')
if url:
ulist.append(url)
print(url + "---" + str(pnum))
print("##################")
2)静态加载的内容
(1)正则;
(2)lxml;
(3)bs4
#!/usr/bin/env python
# -*- coding: utf-8 -*-
string = r'src="(http://imgsrc\.baidu\.com.+?\.jpg)" pic_ext="jpeg"' # 正则表达式字符串 urls = re.findall(string, html)
import requests
from lxml import etree
import urllib
response = requests.get(url)
html = etree.HTML(requests.get(url).content)
res = html.xpath('//div[@class="d_post_content j_d_post_content "]/img[@class="BDE_Image"]/@src') # lxml
import requests
from bs4 import BeautifulSoup
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):支持散点图、线图、柱状图等;
简单例子:
pip2 install Numpy
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a ** 2
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
pip2 install Scipy
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1, 2], [3, 4]])
>>> linalg.det(a)
-2.0
pip2 install pandas
>>> df = pd.DataFrame({ 'A' : pd.date_range("20170802", periods=5), 'B' : pd.Series([11, 22, 33, 44,
55]), 'C' : pd.Categorical(["t","a","b","c","g"])})
>>> df
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
pip2 install Matplotlib
>>> import matplotlib.pyplot as plt
>>> plt.plot([1, 2, 3])
[<matplotlib.lines.Line2D object at 0x113f88f50>]
>>> plt.ylabel("didi")
<matplotlib.text.Text object at 0x110b21c10>
>>> plt.show()
2、高级数据分析库:
scikit-learn:机器学习框架。
图上可以表示出数据小于50,No:需要更多的数据, Yes使用分类器,一直走下去;
由图中,可以看到算法有四类,分类,回归,聚类,降维。
KNN:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''
预测Iris https://en.wikipedia.org/wiki/Iris_flower_data_set '''
# 导入模块
from __future__ import print_function
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# 创建数据
iris = datasets.load_iris()
iris_X = iris.data # 花萼的长宽、 花瓣的长宽
iris_y = iris.target # 花的种类 0, 1, 2
print(iris_X)
print(iris_y)
print(iris.target_names)
# 定义模型-训练模型-预测
X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size = 0.1) # 训练数据10% knn = KNeighborsClassifier() # 创建KNN近邻器
knn.fit(X_train, y_train) # 训练数据
predicts = knn.predict(X_test) # 得到预测结果
# 对比结果
print("#########################")
print(X_test)
print(predicts)
print(y_test)
# 计算预测准确率
print(knn.score(X_test, y_test))
[[ 5. 3.3 1.4 0.2]
[ 5. 3.5 1.3 0.3]
[ 6.7 3.1 5.6 2.4]
[ 5.8 2.7 3.9 1.2]
[ 6. 2.2 5. 1.5]
[ 6. 3. 4.8 1.8]
[ 6.3 2.5 5. 1.9]
[ 5. 3.6 1.4 0.2]
[ 5.6 2.9 3.6 1.3]
[ 6.9 3.2 5.7 2.3]
[ 4.9 3. 1.4 0.2]
[ 5.9 3. 4.2 1.5]
[ 4.8 3. 1.4 0.1]
[ 5.1 3.4 1.5 0.2]
[ 4.7 3.2 1.6 0.2]]
[0 0 2 1 1 2 2 0 1 2 0 1 0 0 0]
[0 0 2 1 2 2 2 0 1 2 0 1 0 0 0]
0.933333333333
Linear Regression
#!/usr/local/bin/python # -*- coding: utf-8 -*- '''
波士顿房价趋势
'''
# 导入模块
from __future__ import print_function
from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# 创建数据
loaded_data = datasets.load_boston() #波士顿的房价
data_X = loaded_data.data
data_y = loaded_data.target
print(data_X)
print(data_y)
# 定义模型-训练模型-预测
model = LinearRegression() # 线性回归
model.fit(data_X, data_y) # 训练数据
print(model.predict(data_X[:4, :])) # 得到预测结果
print(data_y[:4])
# 结果
print("#########################")
X, y = datasets.make_regression(n_samples=100, n_features=1, noise=10) # 生成回归模型数据100个样本, 每个样本一个特征, 高斯噪声
plt.scatter(X, y) # 散点图
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将借力此次战略合作,巩固我们在欧洲和非洲核心市场的优势地位。我们相信滴滴是最理想的 伙伴,能帮助我们成为欧非地区最受欢迎和最有效率的出行选择。”
#!/usr/local/bin/python # -*- coding: utf-8 -*- '''
分析文章关键词
'''
import os
import codecs
import pandas
import jieba
import jieba.analyse
# 格式化数据格式
tagDF = pandas.DataFrame(columns=['filePath', 'content', 'tag1', 'tag2', 'tag3', 'tag4', 'tag5']) try:
with open('./houhuiyang/news.txt', 'r') as f: #载入语料库 content = f.read().strip()
tags = jieba.analyse.extract_tags(content, topK=5) #TF_IDF
tagDF.loc[len(tagDF)] = ["./news.txt", content, tags[0], tags[1], tags[2], tags[3], tags[4]]
print(tagDF)
except Exception, ex:
print(ex)
计算出文章Top5的关键词:出行、滴滴、Taxify、欧非、交通
2、情感分析
情感用语资料:http://www.keenage.com/html/c_bulletin_2007.htm
1)最简单的方式就是基于情感词典的方法;
2)复杂的就是基于机器学习的方法;
pip2 install nltk
>>> import nltk
>>> from nltk.corpus import stopwords #停止词 >>> nltk.download() # 安装语料库
>>> t = "Didi is a travel company"
>>> word_list = nltk.word_tokenize(t)
>>> filtered_words = [word for word in word_list if word not in stopwords.words('english')] ['Didi', 'travel', 'company']
>>> nltk.download('stopwords') #下载停止词
中英文NLP分词区别
1):启发式 Heuristic
2):机器学习/统计法:HMM、CRF
处理流程:raw_text -> tokenize[pos tag] -> lemma / stemming[pos tag] -> stopwords -> word_list
04 Python 分布式计算
pip2 install mrjjob pip2 install pyspark
1)Python 多线程;
2)Python 多进程【multiprocessing】;
3)全局解释器锁GIL;
4)进程间通信Queue;
5)进程池Pool;
6)Python的高阶函数;
map/reduce/filter
7)基于 Linux 的管道的MapReducer 【cat word.log | python mapper.py | python reducer.py | sort -k 2r】
word.log
北京 成都 上海 北京 山西 天津 广州
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''
mapper
'''
import sys
try:
for lines in sys.stdin:
line = lines.split()
for word in line:
if len(word.strip()) == 0:
continue
count = "%s,%d" % (word, 1)
print(count)
except IOError, ex:
print(ex)
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''
reducer
'''
import sys
try:
word_dict = {}
for lines in sys.stdin:
line = lines.split(",")
if len(line) != 2:
continue
word_dict.setdefault(line[0], 0)
word_dict[line[0]] += int(line[1])
for key, val in word_dict.items():
stat = "%s %d" % (key, val)
print(stat)
except IOError, ex:
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用张量这种数据结构来表示所有的数据。
#-*- coding: UTF-8 -*- #author houhuiyang import torch import numpy as np from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt np_data = np.arange(6).reshape((2, 3)) torch_data = torch.from_numpy(np_data) tensor2np = torch_data.numpy() print( "\nnp_data", np_data, #矩阵 "\ntorch_data", torch_data, #张量 "\ntensor to numpy", tensor2np ) # data = [-1, -2, 1, 2, 3] data = [[1, 2], [3, 4]] tensor = torch.FloatTensor(data) # abs sin cos mean平均值 matmul/mm print( "\nnumpy", np.matmul(data, data), "\ntorch", torch.mm(tensor, tensor) ) # tensor variable tensor_v = torch.FloatTensor([[1,2], [3,4]]) variable = Variable(tensor_v, requires_grad=True) # 计算中值 t_out = torch.mean(tensor_v * tensor_v) # x ^ 2 v_out = torch.mean(variable * variable) # 反向传播 print( tensor_v, variable, t_out, v_out ) v_out.backward() # 反向传递 print(variable.grad) # 梯度 ''' y = Wx 线性 y =AF(Wx)非线性 【激励函数 relu/sigmoid/tanh】 ''' x =torch.linspace(-5,5,200) # 从-5到5取200个点 x = Variable(x) x_np = x.data.numpy() y_relu = F.relu(x).data.numpy() y_sigmoid = F.sigmoid(x).data.numpy() y_tanh = F.tanh(x).data.numpy() # y_softplus = F.softplus(x).data.numpy() # 概率图 plt.figure(1, figsize=(8, 6)) # plt.subplot(221) # 绘制子图 plt.plot(x_np, y_relu, c = "red", label = "relu") plt.ylim(-1, 5) plt.legend(loc = "best") plt.show() # plt.subplot(222) plt.plot(x_np, y_sigmoid, c = "red", label = "igmoid") plt.ylim(-0.2, 1.2) plt.legend(loc = "best") plt.show() # plt.subplot(223) plt.plot(x_np, y_tanh, c = "red", label = "subplot") plt.ylim(-1.2, 1.2) plt.legend(loc = "best") plt.show()
搭建简单的神经网络
#-*- coding: UTF-8 -*- #author 守望之心
'''
回归
分类
'''
import torch
from torch.autograd import Variable
import torch.nn.functional as F # 激励函数
import matplotlib.pyplot as plt
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim = 1) # unsqueeze 一维转变为二维 y = x.pow(2) + 0.2 * torch.rand(x.size())
x, y = Variable(x), Variable(y)
# print(x)
# print(y)
# plt.scatter(x.data.numpy(), y.data.numpy())
# plt.show()
class Net(torch.nn.Module): # 继承 torch 的Moudle
def __init__(self, n_features, n_hidden, n_output):
super(Net, self).__init__() # 继承torch __init__
self.hidden = torch.nn.Linear(n_features, n_hidden) # 隐藏层线性输出 self.predict = torch.nn.Linear(n_hidden, n_output) # 输出线性层
def forward(self, x):
x = F.relu(self.hidden(x)) # 激励函数 x = self.predict(x) # 输出值
return x
net = Net(1, 10, 1) # 输入值, 隐藏层10,10个神经元, 1个输出值 print(net) # 输出搭建的神经网络结构
plt.ion()
plt.show()
# 训练工具
optimizer = torch.optim.SGD(net.parameters(), lr = 0.5) # 传入net的所有值, lr是学习率 loss_func = torch.nn.MSELoss() # 均方差
print(net.parameters())
for t in range(100):
prediction = net(x) #喂给net 训练数据x, 输出预测值 loss = loss_func(prediction, y) # 计算两者误差
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % 5 == 0:
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), "r-", lw = 5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)
plt.ioff()
plt.show()
06 数学 微积分
1、极限:
无穷大无穷小阶数;
2、微分学:
导数:
1)导数就是曲线的斜率,是曲线变化快慢的反应;
2)二阶导数是斜率变化快慢的反应,表现曲线的凸凹性;
泰勒级数逼近
牛顿法和梯度下降;
3、Jensen不等式:
凸函数;Jensen不等式
概率论:
1、积分学:
牛顿-莱布尼茨公式
2、概率空间
随机变量与概率:概率密度函数的积分;条件概率;共轭分布;
概率分布:
1)两点分布/贝努力分布;
2)二项分布;
3)泊松分布;
4)均匀分布;
5)指数分布;
6)正态分布/高斯分布;
3、大数定律和中心极限
线性代数:
1)矩阵
2)线性回归;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Web Data Mining
Bing Liu / Springer / 2006-12-28 / USD 59.95
Web mining aims to discover useful information and knowledge from the Web hyperlink structure, page contents, and usage data. Although Web mining uses many conventional data mining techniques, it is n......一起来看看 《Web Data Mining》 这本书的介绍吧!