Python常用分类预测模型
一、感知机算法
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import os
os. getcwd ( )
os. chdir ( r'D:\data05' )
data = pd. read_csv ( 'two_class_data.csv' , header= 0 )
x = data. loc[ : , [ 'x' ] ] ##输出的是dataframe类型
y = data. loc[ : , [ 'y' ] ]
c = data. loc[ : , [ 'class' ] ]
x1= data[ 'x' ] ##输出的是Series类型
y1= data[ 'y' ]
cl= data[ 'class' ]
plt. scatter ( x1, y1, c= cl) ##Series类型的可根据类别绘图
from sklearn. model_selection import train_test_split
from sklearn. linear_model import Perceptron ## 引用感知机Perceptron模块
feature = data[ [ 'x' , 'y' ] ] ##data[ [ 'x' ] ] 输出的是数据框类型;data[ [ 'x' ] ] . values输出的是多维数组数据
target = data[ 'class' ] ##data[ 'x' ] 输出的是Series类型
####分割训练集和测试集
X_train , X_test , y_train , y_test = train_test_split ( feature , target ,
test_size= 0.3 , random_state= 50 )
##train_test_split用于将矩阵随机划分为训练子集和测试子集,random_state为随机种子数,test_size为测试集数所占比例
print ( X_train. shape) ##返回矩阵的维度
model = Perceptron ( max_iter= 1000 , tol= 1e-3 )
###target不能使用数据框类型,否则会报警告信息
model. fit ( X_train , y_train)
results = model. predict ( X_test)
print ( results)
print ( list ( enumerate ( results) ) )
###################绘制散点图
plt. figure ( figsize= ( 9 , 8 ) ) ##figsize设置图表的长宽
# 以默认样式绘制训练数据
plt. scatter ( X_train. iloc[ : , 0 ] , X_train. iloc[ : , 1 ] , alpha= 0.3 ) ##alpha为指定散点透明度
# 以方块样式绘制测试数据
plt. scatter ( X_test. iloc[ : , 0 ] , X_test. iloc[ : , 1 ] , marker= 'o' , c= y_test) ##c为颜色,区别于原始数据
for i, txt in enumerate ( results) :
##enumerate用于将一个可遍历的数据对象组合为一个索引序列,返回数据下标和数据
plt. annotate ( txt, ( X_test. iloc[ i, 0 ] , X_test. iloc[ i, 1 ] ) )
##annotate用于在图形上给数据添加文本注解,txt为注解,()里为数据的坐标
plt. show ( )
####准确率得分
print ( model. score ( X_test , y_test) )
###计算混淆矩阵
from sklearn. metrics import confusion_matrix
conf = confusion_matrix ( y_test , results)
print ( conf)
##################绘制混淆矩阵图
def plot_confusion_matrix ( cm, label_name , title= 'Confusion Matrix' , cmap= plt. cm. Blues) : ##设置形参,包括混淆矩阵、标签名、标题、颜色
plt. imshow ( cm , interpolation= 'nearest' , cmap= cmap) ##plt. imshow为默认配置,cmap为使用自定义的颜色
plt. title ( title) ##设置标题
plt. colorbar ( ) ##生成颜色棒,用以反映颜色深浅所代表的数字含义
tick_marks = np. arange ( len ( label_name) ) ##设置坐标刻度标签的内容
plt. xticks ( tick_marks, label_name, rotation= 0 ) ##设置坐标刻度标签,rotation为将标签旋转的角度
plt. yticks ( tick_marks, label_name)
thresh = cm. max ( ) / 2
for i in range ( len ( cm) ) :
for j in range ( len ( cm[ i] ) ) :
plt. text ( j, i, cm[ i, j] , ha= "center" , va= "center" ,
color= "white" if cm[ i, j] > thresh else "black" ) ##定义混淆矩阵文本标签内容
plt. xlim ( - 0.5 , 1.5 ) ##划定x轴和y轴的边界
plt. ylim ( 1.5 , - 0.5 )
plt. ylabel ( 'True label' , fontsize= 10 ) ##设置坐标轴标签,fontsize为字体大小
plt. xlabel ( 'Predicted label' , fontsize= 10 )
plt. tight_layout ( ) ##使图形更紧致
plot_confusion_matrix ( conf , label_name = [ 0 , 1 ] )
label= [ 0 , 1 ]
print ( range ( len ( label) ) )
plt. show ( )