python机器学习及分析工具《笔记》

python机器学习及分析工具《笔记》

#本文纯属个人笔记

  1. 科学计算包(Scipy)
  2. 绘图库(Matplotlib)
  3. 数据分析包(Pandas)
  4. 机器学习函数库(Scikit-learn)
  5. 统计建模工具库(StatsModels)

科学计算包(Scipy)

求解非线性方程组
使用scipy库的optimize库的fsolve函数

#实例
5x1+3=0
4
x0x0-2sin(x1x2)=0
x1
x2-1.5=0

#代码实现
from scipy.optimize import fsolve
from math import sin,cos
def f(x):
    x0=float(x[0])
    x1=float(x[1])
    x2=float(x[2])
    return[
        5*x1+3,
        4*x0*x0-2*sin(x1*x2),
        x1*x2-1.5
    ]
#上面是函数的定义,下面代码就可以访问这个函数
result=fsolve(f,[1,1,1])
print(result)
print(f(result))

运行结果如下:
在这里插入图片描述

绘图库matplotlib

import matplotlib.pyplot as plt
plt.bar([1,2,4,6,7],[3,2,6,8,4])  #创建条形图
plt.xlabel('bar number')
plt.ylabel("bar height")
plt.show

在这里插入图片描述

#颜色:蓝色(b),红色(r),青色(c)     大多数各颜色是个单词的首字母
#线性:-实线,-.点画线,
#maker参数,标记图形汇总每个数据点,o圆圈,D菱形,h六边形
import numpy as np
import matplotlib.pyplot as plt
import math
import matplotlib
#x是0-2pi的100个点,y是以x为参数的正弦函数值,z是x2为参数计算的余弦值
x=np.linspace(0,-2*np.pi,100)   #linspace指定开始值、终值和元素个数创建一维数组
y=np.sin(x)
z=np.cos(np.power(x,2))
plt.figure(1)  #调用figure创建一个绘图对象,使之成为当前的绘图对象
plt.plot(x,y,label="$sin$",color="red",linewidth=2)   #绘制的曲线的名称sin,必须,此名称在legend中显示
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("First Example")
plt.ylim(-1.2,1.2)    #y轴范围
plt.legend()
plt.show()

在这里插入图片描述

plt.figure(2)
plt.plot(x,z,"b--",label="$cos(x^2)$")
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("Second Example")
plt.ylim(-1.2,1.2)
plt.legend()
plt.show()

在这里插入图片描述
#绘制多窗口图形
#一个绘图对象(figure)可以包括多个轴(axis)
#subplot函数可以快速绘制多个轴的图像

plt.subplot(1,2,1)
plt.plot(x,y,color="red",label="$sin(x)$",linewidth=2)
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("first example")
plt.ylim(-1.2,1.2)
plt.legend()
plt.subplot(1,2,2)
plt.plot(x,z,"b--",label="$cos(x^2)$")
plt.xlabel("Time(x)")
plt.ylabel("Volt")
plt.title("second example")
plt.ylim(-1.2,1.2)
plt.legend()
plt.show()

在这里插入图片描述
#文本注释
#是matplotlib.pyplot模块提供的一个注解函数,可以用来对坐标中的数据进行注解,让人更清晰的得知坐标点意思
#xy – 为点的坐标
#xytext – 为注解内容位置坐标,当该值为None时,注解内容放置在xy处
#arrowprops – 用于设置箭头的形状,类型为字典类型

x=np.arange(0.0,5.0,0.01)
y=np.cos(2*np.pi*x)
plt.plot(x,y)
plt.annotate("local max",xy=(2,1),xytext=(3,1.5),arrowprops=dict(facecolor="black",shrink=0.05),)
plt.ylim(-2,2)
plt.show()

在这里插入图片描述
#中文显示问题

from pylab import *
mpl.rcParams["font.sans-serif"]=["SimHei"]  #显示中文
plt.rcParams["axes.unicode_minus"]=False   #显示负号
plt.plot(x,y,color="red",label="$sin(x)$",linewidth=2)
plt.xlabel("时间(秒)")
plt.ylabel("电压")
plt.title("正弦波")
plt.ylim(-1.2,1.2)
plt.legend()
plt.show()

在这里插入图片描述

数据分析包(Pandas)

#基本数据结构series[一维]序列,DataFrame[二维]数组
#基本使用方法

import pandas as pd
from pandas import Series, DataFrame

在这里插入图片描述
#通过传递一个list对象创建series,默认创建整型索引

a=Series([4,-3,24,5])
print("创建series:\n",a)    ##\n换行

在这里插入图片描述
#通过创建索引,来确定每一个数据点的series

b=Series([4,7,-3,2],index=["s","w","k","v"])
print("创建Series:\n",b)    #\n换行

在这里插入图片描述
#通过字典创建Series

sdata={
    
    "ohibg":56789,"fhjcrt":986678,"dycgh":964764}
c=Series(sdata)
print("通过字典创建Series:\n",c)

在这里插入图片描述
##DataFrame同样可以接受多种输入:list,dicts,series和DataFrame等

机器学习函数库(Scikit-learn)

1.Scikit-learn库
##A 分类 ——识别给定对象的所属类别【支持向量机SVM,k-近邻,逻辑回归,随机森林,决策树,多层感知机MLP神经网络】
##B 回归 ——预测与给定对象相关联的连续值属性【支持向量回归SVR,脊回归,Lasso回归,弹性回归,最小角回归LARS,贝叶斯回归】
##C 聚类 ——自动识别具有相似属性的给定对象,并将其分组为集合【无监督】
##D 数据降维 ——减少要考虑的随机变量的个数【主成分分析PCA,非负矩阵分解NMF,特征选择】
##E 模型选择 ——对给定参数和模型的比较、验证和选择,通过参数调整来调整精度【格点搜索,交叉验证等】
##F 数据预处理 ——数据的特征提取和归一化

from sklearn.datasets import load_iris   #鸢尾花例子,简单分类
iris=load_iris()
print(iris.data)

[[5.1 3.5 1.4 0.2]
[4.9 3. 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]
[5.4 3.9 1.7 0.4]
[4.6 3.4 1.4 0.3]
[5. 3.4 1.5 0.2]
[4.4 2.9 1.4 0.2]
[4.9 3.1 1.5 0.1]
[5.4 3.7 1.5 0.2]
[4.8 3.4 1.6 0.2]
[4.8 3. 1.4 0.1]
[4.3 3. 1.1 0.1]
[5.8 4. 1.2 0.2]
[5.7 4.4 1.5 0.4]
[5.4 3.9 1.3 0.4]
[5.1 3.5 1.4 0.3]
[5.7 3.8 1.7 0.3]
[5.1 3.8 1.5 0.3]]
[4.9 3.1 1.5 0.1]
[5. 3.2 1.2 0.2]
[5.5 3.5 1.3 0.2]
[4.9 3.1 1.5 0.1]
[4.4 3. 1.3 0.2]
[5.1 3.4 1.5 0.2]
[5.5 2.3 4. 1.3]
[6.5 2.8 4.6 1.5]
[5.7 2.8 4.5 1.3]
[6.3 3.3 4.7 1.6]
[6.3 3.3 6. 2.5]
[5.8 2.7 5.1 1.9]
[7.1 3. 5.9 2.1]
[6.3 2.9 5.6 1.8]
[6.3 2.5 5. 1.9]
[6.5 3. 5.2 2. ]
[6.2 3.4 5.4 2.3]
[5.9 3. 5.1 1.8]]
#数据太长,删除了部分

print(iris.target)  #输出真实标签
print(len(iris.target))   #输出标签长度
print(iris.data.shape)  #输出标签行状
print(iris.target_names)  #输出数据标签的名字

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]
150
(150, 4)
[‘setosa’ ‘versicolor’ ‘virginica’]

#数据集的划分
#(1)使用train_test_split对数据集进行划分
#需要用到sklearn.model_selection函数
#X_train:训练集的特征
#X_test:测试集的特征
#y_train:训练集的标签
#y_test:测试集的标签
#train_target:所要划分的样本结果
#test_size:样本占比
#random_state:随机种子

#实例
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn import svm
iris=load_iris()
print(iris.data.shape)
print(iris.target.shape)
X_train,X_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=4,random_state=0)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
print(iris.data[:5])
print(X_train[:5])

(150, 4)
(150,)
(146, 4)
(146,)
(4, 4)
(4,)
[[5.1 3.5 1.4 0.2]
[4.9 3. 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]]
[[5. 3.4 1.5 0.2]
[6.3 3.3 6. 2.5]
[5. 3.5 1.3 0.3]
[6.7 3.1 4.7 1.5]
[6.8 2.8 4.8 1.4]]

#(2)使用cross_val_score对数据进行交叉验证,并对每次验证效果进行测评

from sklearn.model_selection import cross_val_score
clf=svm.SVC(kernel="linear",C=1)   #使用SVM模型进行验证
scores=cross_val_score(clf,iris.data,iris.target,cv=5)   #5折交叉验证
print(scores)
print(scores.mean())

[0.96666667 1. 0.96666667 0.96666667 1. ]
0.9800000000000001

#上面代码使用过程,除默认交叉验证方式外,可以对交叉验证方式进行指定,如验证次数,训练集测试集划分比例等。

from sklearn.model_selection import ShuffleSplit   
#使用ShuffleSplit将数据集打乱
n_samples=iris.data.shape[0]
cv=ShuffleSplit(n_splits=3,test_size=.3,random_state=12)    
#n_splits表示将数据集分三次,每次训练集大小占原数据集的70%
cross_val_score(clf,iris.data,iris.target,cv=cv)

array([1. , 0.97777778, 0.97777778])

#(3)K折交叉验证
#将数据集分成K份,K折就是将数据集通过K次分割,使所有数据即在训练集出现过。又在测试集出现过
#每次分割不会重叠,相当于无放回抽样

from sklearn.model_selection import KFold
X=["a","b","c","d","e","f"]
kf=KFold(n_splits=2)  #2折交叉验证
for train, test in kf.split(X):
    print(train,test)
    print(np.array(X)[train],np.array(X)[test])
    print("\n")

[3 4 5] [0 1 2]
[‘d’ ‘e’ ‘f’] [‘a’ ‘b’ ‘c’]

[0 1 2] [3 4 5]
[‘a’ ‘b’ ‘c’] [‘d’ ‘e’ ‘f’]

#(4)LeaveOneOut验证
##其实就是KFold的一个特例,就是数据集太少时使用
#例如,N个样本采用LeaveOneOut验证法,就是将样本打乱,均匀分成N份,轮流选择N-1份训练,剩余一份做验证,计算预测误差平方和。
#最后把N次的预测误差平方和做平均作为选择最优模型结构的依据。

from sklearn.model_selection import LeaveOneOut
X=["a","b","c","d","e","f"]
loo=LeaveOneOut()
for train,test in loo.split(X):
    print(train,test)
    print(np.array(X)[train],np.array(X)[test])

#可以看出数据集个数为6个,每次训练为5个数据,验证集只有1个数据,反复拆分5次

[1 2 3 4 5] [0]
[‘b’ ‘c’ ‘d’ ‘e’ ‘f’] [‘a’]
[0 2 3 4 5] [1]
[‘a’ ‘c’ ‘d’ ‘e’ ‘f’] [‘b’]
[0 1 3 4 5] [2]
[‘a’ ‘b’ ‘d’ ‘e’ ‘f’] [‘c’]
[0 1 2 4 5] [3]
[‘a’ ‘b’ ‘c’ ‘e’ ‘f’] [‘d’]
[0 1 2 3 5] [4]
[‘a’ ‘b’ ‘c’ ‘d’ ‘f’] [‘e’]
[0 1 2 3 4] [5]
[‘a’ ‘b’ ‘c’ ‘d’ ‘e’] [‘f’]

##同理,上面代码也可以修改为K折交叉验证,即K=N
from sklearn.model_selection import KFold
X=["a","b","c","d","e","f"]
kf=KFold(n_splits=len(X))
for train,test in kf.split(X):
    print(train,test)
    print(np.array(X)[train],np.array(X)[test])
    print("\n")   #换行

[1 2 3 4 5] [0]
[‘b’ ‘c’ ‘d’ ‘e’ ‘f’] [‘a’]

[0 2 3 4 5] [1]
[‘a’ ‘c’ ‘d’ ‘e’ ‘f’] [‘b’]

[0 1 3 4 5] [2]
[‘a’ ‘b’ ‘d’ ‘e’ ‘f’] [‘c’]

[0 1 2 4 5] [3]
[‘a’ ‘b’ ‘c’ ‘e’ ‘f’] [‘d’]

[0 1 2 3 5] [4]
[‘a’ ‘b’ ‘c’ ‘d’ ‘f’] [‘e’]

[0 1 2 3 4] [5]
[‘a’ ‘b’ ‘c’ ‘d’ ‘e’] [‘f’]

统计建模工具库(StatsModels)

#StateModels以前时Scikits的一部分,是Scipy统计函数的补充
#包括线性模型、离散选择模型、时间序列分析、一系列描述统计学及非参数检验等。

#下载安装成功后,进入测试,看是否可以使用
#这段程序显示一个时间序列图形
from __future__ import print_function
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.graphics.api import qqplot
#给出时间序列数据
data=[10930,10318,10432,10848,10483,9384,10384,9302,10462,9421,7923,10395,10473,9472,9302,8392,10383,10238,10938,10392,10392,10823,10382,7392,9232,10382]
data=np.array(data,dtype=np.float)     #转换数据类型
data=pd.Series(data)
data.index=pd.Index(sm.tsa.datetools.dates_from_range("2001","2026"))
data.plot(figsize=(12,8))
plt.show()

tguo
通过上面程序运行结果可知,这个库可正常运行。

猜你喜欢

转载自blog.csdn.net/m0_45993955/article/details/115097474