数据挖掘简介
1.什么是数据挖掘?从大量数据(含文本)中挖掘出隐含的、未知的、对决策有潜在价值的关系、模式和趋势,并用这些知识和规则建立用于决策支持的模型,提供预测性决策支持的关系、工具和过程;2.数据挖掘能做什么?利用机器学习的方法,帮助企业提取数据中蕴含的商业价值,提高企业的竞争力;3.怎么做?(数据挖掘建模过程)3.1.定义挖掘目标考虑系统完后后能达到什么样的
1.什么是数据挖掘?
从大量数据(含文本)中挖掘出隐含的、未知的、对决策有潜在价值的关系、模式和趋势,并用这些知识和规则建立用于决策支持的模型,提供预测性决策支持的关系、工具和过程;
2.数据挖掘能做什么?
利用机器学习的方法,帮助企业提取数据中蕴含的商业价值,提高企业的竞争力;
3.怎么做?(数据挖掘建模过程)
3.1.定义挖掘目标
考虑系统完后后能达到什么样的结果?
3.2 数据取样
3.2.1 数据抽取的标准:相关性、可靠性、有效性
相关性和可靠性保证数据正确性,从而得出正确的模型,有效性保证数据处理量,减少成本;
3.2.2 获取数据抽样方式:
随机抽样:按一定的概率抽取
等距抽样:在相等的距离使用随机抽样
分层抽样:把样本分成若干层,每层上使用不同的概率抽样
从起始顺序抽样:从起始位置开始,给定百分比
分类抽样:将数据分类抽取
3.3 数据探索
异常值分析、缺失值分析、相关分析
3.4 数据预处理
降维处理、缺失值处理
3.5 挖掘建模
哪类问题?哪种算法?
3.6 模型评价
4.数据挖掘工具
- SAS Enterprise Miner
- IBM SPSS Modeler
- SQL Server
- Python
- WEKA
- KNIME
- RapidMiner
- TipDMS
5.Python数据分析工具
- Numpy:提供数组支持,以及相应的高效的处理函数
- Scipy:提供矩阵支持,以及矩阵相关的数值计算模块
- Matplotlib:强大的数据可视化工具,作图库
- Pandas:数据分析和探索工具
- StatsModels:统计建模和计量经济学,描述统计,统计模型和推断
- Keras:深度学习库,用于建立神经网络以及深度学习模型
- Gensim:文本主体模型的库,文本挖掘可能用到
- Pillow:图片处理
- OpenCV:视频处理
6. 数据挖掘常用库使用
- Numpy库
#numpy库的简单使用
#导入numpy并重新命名为np
import numpy as np
a = np.array([1,2,3,6,4,5])
#输出a的内容和其数据类型
print(a,type(a))
#数组从0开始,前面省略表示从0开始,后面省略表示至结束
print(a[:3])
print(a[1:])
#取数组最小值
print(a.min())
#数组排序
a.sort()
print(a)
#二维数组等同于两个一维数组,最后形成一个整体
b = np.array([[1,2,3],[4,5,6]])
print(b)
#数组对应相乘
print(b*b)
[1 2 3 6 4 5] <class 'numpy.ndarray'>
[1 2 3]
[2 3 6 4 5]
1
[1 2 3 4 5 6]
[[1 2 3]
[4 5 6]]
[[ 1 4 9]
[16 25 36]]
参考文档
http://www.numpy.org/
http://reverland.org/python/2012/08/22/numpy/
2. Scipy库
#Scipy:最优化、线性代数、积分、插值、拟合、特殊函数、快速傅里叶变换、信号处理和图像处理
#常微分方程求解等其他运算
'''
#求解非线性方程组:
2x1-x2^2=1
x1^2-x2 =2
'''
#导入求解方程的函数
from scipy.optimize import fsolve
#定义函数:将解的方程组转化为求最优化问题
def f(x):
x1 = x[0]
x2 = x[1]
return [2*x1-x2**2-1,x1**2-x2-2]
#调用函数,初始值为【1,1】,不断优化
result = fsolve(f,[1,1])
print(result)
'''
数值积分
'''
#导入积分函数
from scipy import integrate
#定义函数:说明积分内容
def h(x):
return (x**2)
#积分结果和误差
pi_2,err = integrate.quad(h,-1,1)
#积分结果为pi的一半
print(pi_2)
[ 1.91963957 1.68501606]
0.6666666666666666
参考文档
http://www.scipy.org/
http://reverland.org/python/2012/08/24/scipy
3.Matplotlib库
#matplotlib:作图
#导入Matplotlib函数包
import numpy as np
import matplotlib.pyplot as plt
#定义函数
#x从0-10,分成1000份
x = np.linspace(0,10,1000)
#因变量y、z
y = np.sin(x)+1
z = np.cos(x**2)+1
#设置大小,宽度和高度
plt.figure(figsize=(6,4))
#设置标签、线条颜色、大小
plt.plot(x,y,label="$\sin x+1$",color="red",linewidth=2)
plt.plot(x,z,label="$\cos(x^2+1$)")
#坐标名称
plt.xlabel("Time(s)")
plt.ylabel("Volt")
#标题
plt.title("A Sample Example")
#y轴的范围
plt.ylim(0,2.2)
#设置标签显示位置
plt.legend(loc = 1)'''
loc参数说明:
upper right:1
upper left:2
lower left:3
lower right:4
right:5
center left:6
center right:7
lower center:8
upper center:9
center:10
'''
plt.show()
import pandas as pd
#创建序列s
s = pd.Series([1,2,3],index=['a','b','c'])
#创建DataFrame
d = pd.DataFrame([[1,2,3],[4,5,6]],columns=['a','b','c'])
#用已有的序列来创建表格
d2 = pd.DataFrame(s)
#预览前五行数据
print(d.head())
#数据基本统计量描述
print(d.describe())
#读取Excel文件,创建DataFrame
Excel_Reader = pd.read_excel("E:/MachineLearning-data/news.xlsx")
#print(Excel_Reader)
#读取文本格式数据,并指定其编码
Csv_Reader = pd.read_csv("E:/MachineLearning-data/Delivery.csv",encoding="utf-8")
#print(Csv_Reader)
a b c
0 1 2 3
1 4 5 6
a b c
count 2.00000 2.00000 2.00000
mean 2.50000 3.50000 4.50000
std 2.12132 2.12132 2.12132
min 1.00000 2.00000 3.00000
25% 1.75000 2.75000 3.75000
50% 2.50000 3.50000 4.50000
75% 3.25000 4.25000 5.25000
max 4.00000 5.00000 6.00000
参考网址
http://pandas.pydata.org/pandas-docs/stable/
http://jingyan.baidu.com/season/43456
5.StatsModels库
''' StatsModels:数据的统计建模分析 ''' #StatsModels来进行ADF平稳性检验 from statsmodels.tsa.stattools import adfuller as ADF import numpy as np c = ADF(np.random.rand(100)) print(c)
(-9.0156962694242448, 5.9591505643136473e-15, 0, 99, {'1%': -3.4981980821890981, '5%': -2.8912082118604681, '10%': -2.5825959973472097}, 27.663869500747978)
参考文档
http://statsmodels.sourceforge.net/stable/index.html
http://jingyan.baidu.com/season/43456
6.Scikit-Learn库
'''
Scikit-Learn:机器学习相关库
1.所有模型提供的接口
model.fit():训练模型,监督模型为fit(X,y),非监督模型为fit(X)
2.监督模型提供的接口
model.predict(X_new):预测新样本
model.predict_proba(X_new):预测概率,仅对某些模型管用,如LR
3.非监督模型接口
model.transform():从数据中学到的新的“基空间”
model.fit_transform():从数据中学到新的基并将这个数据按照这组“基”进行转换
'''
#导入数据集
from sklearn import datasets
#加载数据集
iris = datasets.load_iris()
#查看数据集大小
print(iris.data.shape)
from sklearn.linear_model import LinearRegression
model = LinearRegression()
print(model)
#导入svm模型
from sklearn import svm
#建立线性SVM分类器
clf = svm.LinearSVC()
#用数据训练模型
clf.fit(iris.data,iris.target)
#训练好模型后,输入新的数据进行预测
result = clf.predict([5.0,3.6,1.3,0.25])
#查询训练好模型的参数
print(result)
clf.coef_
(150, 4)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
[0]
D:\Program Files\Python\Anaconda\lib\site-packages\sklearn\utils\validation.py:395: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
参考文档
http://scikit-learn.org/
7.Keras库
安装Keras详见
#-*- coding: utf-8 -*-#使用神经网络算法预测销量高低
import pandas as pd
import matplotlib.pyplot as plt #导入作图库
from sklearn.metrics import confusion_matrix #导入混淆矩阵函数
#参数初始化
inputfile = 'E:/MachineLearning-data/sales_data.xls'
data = pd.read_excel(inputfile, index_col = u'序号') #导入数据
#对混淆矩阵图进行设定
def cm_plot(y, yp):
cm = confusion_matrix(y, yp) #混淆矩阵
plt.matshow(cm, cmap=plt.cm.Greens) #画混淆矩阵图,配色风格使用cm.Greens,更多风格请参考官网。
plt.colorbar() #颜色标签
for x in range(len(cm)): #数据标签
for y in range(len(cm)):
plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center')
plt.ylabel('True label') #坐标轴标签
plt.xlabel('Predicted label') #坐标轴标签
return plt
#数据是类别标签,要将它转换为数据
#用1来表示“好”、“是”、“高”这三个属性,用0来表示“坏”、“否”、“低”
data[data == u'好'] = 1
data[data == u'是'] = 1
data[data == u'高'] = 1
data[data != 1] = 0
x = data.iloc[:,:3].as_matrix().astype(int)
y = data.iloc[:,3].as_matrix().astype(int)
from keras.models import Sequential
from keras.layers.core import Dense, Activation
model = Sequential() #建立模型
model.add(Dense(input_dim = 3, output_dim = 10))
model.add(Activation('relu')) #用relu函数作为激活函数,能够大幅提供准确度
model.add(Dense(input_dim = 10, output_dim = 1))
model.add(Activation('sigmoid')) #由于是0-1输出,用sigmoid函数作为激活函数
model.compile(loss = 'binary_crossentropy', optimizer = 'adam')
#编译模型。由于我们做的是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary
#另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读帮助文件。
#求解方法我们指定用adam,还有sgd、rmsprop等可选
model.fit(x, y, nb_epoch = 1000, batch_size = 10) #训练模型,学习一千次
yp = model.predict_classes(x).reshape(len(y)) #分类预测
cm_plot(y,yp).show() #显示混淆矩阵可视化结果
部分数据
序号 | 天气 | 是否周末 | 是否有促销 | 销量 |
1 | 坏 | 是 | 是 | 高 |
2 | 坏 | 是 | 是 | 高 |
3 | 坏 | 是 | 是 | 高 |
4 | 坏 | 否 | 是 | 高 |
5 | 坏 | 是 | 是 | 高 |
6 | 坏 | 否 | 是 | 高 |
7 | 坏 | 是 | 否 | 高 |
8 | 好 | 是 | 是 | 高 |
9 | 好 | 是 | 否 | 高 |
10 | 好 | 是 | 是 | 高 |
11 | 好 | 是 | 是 | 高 |
12 | 好 | 是 | 是 | 高 |
13 | 好 | 是 | 是 | 高 |
14 | 坏 | 是 | 是 | 低 |
8.Gensim库
在windows下安装Gensim,使用命令行,输入:
pip install gensim
安装完成后使用
'''
Gensim:用来处理语言方面的任务,主要方向为自然语言处理
'''
import gensim,logging
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',level=logging.INFO)
sentences = [["first","sentence"],["second","sentence"]]
model = gensim.models.Word2Vec(sentences,min_count=1)
print(model["sentence"])
[ -6.33527467e-04 -3.24630644e-03 4.81502898e-03 ..., -4.40569222e-03
-2.37366421e-05 1.35756179e-03]
更多推荐
所有评论(0)