数据挖掘与机器学习:Python机器学习软件包Scikit-Learn的学习与运用

目录

第1关:使用scikit-learn导入数据集

任务描述:

相关知识:

编程要求:

测试说明:

第2关:数据预处理 — 标准化

任务描述:

相关知识:

Z-score 标准化

 min-max 标准化

编程要求:

测试说明:

第3关:文本数据特征提取

第4关:使用scikit-learn分类器SVM对digits数据分类

第5关:模型持久化

第6关:模型评估-量化预测效果


第1关:使用scikit-learn导入数据集

任务描述:

使用 scikit-learn 的datasets模块导入 iris 数据集,并打印数据。

相关知识:

scikit-learn 包括一些标准数据集,不需要从外部下载,可直接导入使用,比如与分类问题相关的Iris数据集和digits手写图像数据集,与回归问题相关的波士顿房价数据集。

以下列举一些简单的数据集,括号内表示对应的问题是分类还是回归:

  1. #加载并返回波士顿房价数据集(回归)
  2. load_boston([return_X_y])
  3. #加载并返回iris数据集(分类)
  4. load_iris([return_X_y])
  5. #加载并返回糖尿病数据集(回归)
  6. load_diabetes([return_X_y])
  7. #加载并返回数字数据集(分类)
  8. load_digits([n_class, return_X_y])
  9. #加载并返回linnerud数据集(多分类)
  10. load_linnerud([return_X_y])

这些标准数据集采用类字典的对象格式存储,比如.data表示原始数据,是一个(n_samples,n_features)二维数组,通过.shape可以得到二维数组大小,.target表示存储数据类别即标签。
下面我们将利用datasets加载数据集digits作为示例,如下图所示:

 在命令行输入python进入 Python 终端,>>>表示 Python 终端提示符,输入 Python 命令即可执行。y[:5]表示标签的前 5 个数据。

编程要求:

本关任务是,使用 scikit-learn 的datasets模块导入iris数据集,提取前 5 条原数据、前 5 条数据标签及原数据的数组大小。 请按照编程要求,补全右侧编辑器Begin-End区间的代码。

from sklearn import datasets
def getIrisData():
    '''
    导入Iris数据集
    返回值:
    X - 前5条训练特征数据
    y - 前5条训练数据类别
    X_shape - 训练特征数据的二维数组大小
    '''
    #初始化
    X = [] 
    y = [] 
    X_shape = () 
    #   请在此添加实现代码   #
    #********** Begin *********#
 
    #********** End **********#
    return X,y,X_shape

测试说明:

本关的测试文件是step1/testImportData.py,该代码负责对你的实现代码进行测试,注意step1/testImportData.py 不能被修改,该测试代码具体如下:

import importData
X,y,X_shape = importData.getIrisData()
print(X)
print(y)
print(X_shape)
from sklearn import datasets
def getIrisData():

    '''
    导入Iris数据集

    返回值:
    X - 前5条训练特征数据
    y - 前5条训练数据类别
    X_shape - 训练特征数据的二维数组大小
    '''
    #初始化
    X = [] 
    y = [] 
    X_shape = () 
    #   请在此添加实现代码   #
    #********** Begin *********#
    iris = datasets.load_iris()
    X=iris.data[:5]
    y = iris.target[:5]
    X_shape = iris.data.shape
    #********** End **********#

    return X,y,X_shape

第2关:数据预处理 — 标准化

任务描述:

在前一关卡,我们已经学会了使用 sklearn 导入数据,然而原始数据总是比较杂乱、不规整的,直接加载至模型中训练,会影响预测效果。本关卡,将学习使用sklearn 对导入的数据进行预处理。

相关知识:

原始数据存在的几个问题:不一致、重复、含噪声、维度高。数据挖掘中,数据预处理包含数据清洗、数据集成、数据变换和数据归约几种方法,在这里不过多叙述预处理方法细节。接下来将简单介绍,如何通过调用 sklearn 中的模块进行数据预处理。

sklearn.preprocessing 模块提供很多公共的方法,将原始不规整的数据转化为更适合分类器的具有代表性的数据。一般说来,使用标准化后的数据集训练学习模型具有更好的效果。

数据标准化的方法有很多种,常用的有“最小—最大标准化”、“Z-score标准化”等等。经过上述标准化处理,各属性值都处于同一个数量级别上,可以进行综合数据分析。

Z-score 标准化

这种方法基于原始数据的均值(mean)和标准差(standard deviation)进行数据的标准化。将 A 的原始值 x 使用 Z-score 标准化到 x'。
Z-score 标准化方法适用于属性A的最大值和最小值未知的情况,或有超出取值范围的离群数据的情况,其公式为:

新数据=(原数据-均值)/标准差

sklearn.preprocessing.scale函数,可以直接将给定数据进行标准化。

 标准化处理后,数据的均值和方差:

 sklearn.preprocessing.StandardScaler类实现了 Transformer 接口,可以保存训练数据中的参数(均值 mean_、缩放比例 scale_),并能将其应用到测试数据的标准化转换中。

 将标准化转换器应用到新的测试数据:

 min-max 标准化

min-max 标准化方法是对原始数据进行线性变换。设 minA 和 maxA 分别为属性 A 的最小值和最大值,将 A 的一个原始值 x 通过 min-max 标准化,映射成在区间[0,1]中的值 x',其公式为:
新数据=(原数据-极小值)/(极大值-极小值)

sklearn.preprocessing.MinMaxScaler将属性缩放到一个指定的最大和最小值(通常是1-0)之间。
MinMaxScaler 中可以通过设置参数feature_range=(min, max)指定最大最小区间。其具体的计算公式为:

  1. X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
  2. X_scaled = X_std * (max - min) + min

 将标准化缩放,应用到新的测试数据:

编程要求:

本关任务希望对于 California housing 数据集进行标准化转换。 代码中已通过fetch_california_housing函数加载好了数据集 California housing 数据集包含 8 个特征,分别是['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude'],可通过dataset.feature_names访问数据具体的特征名称,通过在上一关卡的学习,相信大家对于原始数据的查看应该比较熟练了,在这里不过多说明。

本次任务只对 California housing 数据集中的两个特征进行操作,分别是第 1 个特征 MedInc,其数据服从长尾分布;第 6 个特征 AveOccup,数据中包含大量离群点。

本关分成为几个子任务: 1.使用 MinMaxScaler 对特征数据 X 进行标准化转换,并返回转换后的特征数据的前 5 条; 要补充的代码块如下:

def getMinMaxScalerValue():
    '''
    对特征数据X进行MinMaxScaler标准化转换,并返回转换后的数据前5条
    返回值:
    X_first5 - 数据列表
    '''
    X_first5 = []
    #   请在此添加实现代码   #
    # ********** Begin *********#
    # ********** End **********#
    return X_first5

 2.使用 scale 对目标数据 y 进行标准化转换,并返回转换后的前 5 条数据; 要补充的代码块如下:

def getScaleValue():
    '''
        对目标数据y进行简单scale标准化转换,并返回转换后的数据前5条
        返回值:
        y_first5 - 数据列表
        '''
    y_first5 = []
    #   请在此添加实现代码   #
    # ********** Begin *********#
    # ********** End **********#
    return y_first5

 3.使用 StandardScaler 对特征数据 X 的进行标准化转换,并返回转换后的均值和缩放比例值。 要补充的代码块如下:

def getStandardScalerValue():
    '''
    对特征数据X进行StandardScaler标准化转换,并返回转换后的数据均值和缩放比例
    返回值:
    X_mean - 均值
    X_scale - 缩放比例值
    '''
    X_mean = None
    X_scale = None
    #   请在此添加实现代码   #
    #********** Begin *********#
    #********** End **********#
    return X_mean,X_scale

测试说明:

平台将运行您补全的代码文件,比对您所编写函数的返回值与正确的数值,只有所有数据全部计算正确才能进入下一关。

from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import scale
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import fetch_california_housing
'''
Data descrption:
The data contains 20,640 observations on 9 variables.
This dataset contains the average house value as target variable
and the following input variables (features): average income,
housing average age, average rooms, average bedrooms, population,
average occupation, latitude, and longitude in that order.
dataset : dict-like object with the following attributes:
    dataset.data : ndarray, shape [20640, 8]
        Each row corresponding to the 8 feature values in order.
    dataset.target : numpy array of shape (20640,)
        Each value corresponds to the average house value in units of 100,000.
    dataset.feature_names : array of length 8
        Array of ordered feature names used in the dataset.
    dataset.DESCR : string
        Description of the California housing dataset.
'''
dataset = fetch_california_housing("./step4/")
X_full, y = dataset.data, dataset.target
#抽取其中两个特征数据
X = X_full[:, [0, 5]]
def getMinMaxScalerValue():
    '''
    对特征数据X进行MinMaxScaler标准化转换,并返回转换后的数据前5条
    返回值:
    X_first5 - 数据列表
    '''
    X_first5 = []
    #   请在此添加实现代码   #
    # ********** Begin *********#
    min_max=MinMaxScaler()
    X_first5=min_max.fit_transform(X)[:5]
    # ********** End **********#
    return X_first5
def getScaleValue():
    '''
        对目标数据y进行简单scale标准化转换,并返回转换后的数据前5条
        返回值:
        y_first5 - 数据列表
        '''
    y_first5 = []
    #   请在此添加实现代码   #
    # ********** Begin *********#
    y_first5=scale(y)[:5]
    # ********** End **********#
    return y_first5
def getStandardScalerValue():
    '''
    对特征数据X进行StandardScaler标准化转换,并返回转换后的数据均值和缩放比例
    返回值:
    X_mean - 均值
    X_scale - 缩放比例值
    '''
    X_mean = None
    X_scale = None
    #   请在此添加实现代码   #
    #********** Begin *********#
    a=StandardScaler().fit(X)
    X_mean=a.mean_
    X_scale=a.scale_
    #********** End **********#
    return X_mean,X_sc

第3关:文本数据特征提取

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer


categories = [
    'alt.atheism',
    'talk.religion.misc',
]

# 加载对应目录的新闻数据,包含857 个文档
data = fetch_20newsgroups("./step5/",subset='train', categories=categories)
X = data.data

def transfer2CountVector():
    '''
    使用CountVectorizer方法提取特征向量,返回词汇表大小和前五条特征向量

    返回值:
    vocab_len - 标量,词汇表大小
    tokenizer_list - 数组,对测试字符串test_str进行分词后的结果
    '''

    vocab_len = 0

    test_str = "what's your favorite programming language?"
    tokenizer_list = []

    #   请在此添加实现代码   #
    # ********** Begin *********#
    v=CountVectorizer()
    v.fit(X)
    vocab_len=len(v.vocabulary_)
    jxh=v.build_analyzer()
    tokenizer_list=jxh(test_str)
    # ********** End **********#

    return vocab_len,tokenizer_list

def transfer2TfidfVector():
    '''
        使用TfidfVectorizer方法提取特征向量,并将向量化转换器应用到新的测试数据

        TfidfVectorizer()方法的参数设置:
        min_df = 2,stop_words="english"

        test_data - 需要转换的原数据

        返回值:
        transfer_test_data - 二维数组ndarray
        '''

    test_data = ['Once again, to not believe in God is different than saying\n>I BELIEVE that God does not exist. I still maintain the position, even\n>after reading the FAQs, that strong atheism requires faith.\n>\n \nNo it in the way it is usually used. In my view, you are saying here that\ndriving a car requires faith that the car drives.\n \nFor me it is a conclusion, and I have no more faith in it than I have in the\npremises and the argument used.\n \n \n>But first let me say the following.\n>We might have a language problem here - in regards to "faith" and\n>"existence". I, as a Christian, maintain that God does not exist.\n>To exist means to have being in space and time. God does not HAVE\n>being - God IS Being. Kierkegaard once said that God does not\n>exist, He is eternal. With this said, I feel it\'s rather pointless\n>to debate the so called "existence" of God - and that is not what\n>I\'m doing here. I believe that God is the source and ground of\n>being. When you say that "god does not exist", I also accept this\n>statement - but we obviously mean two different things by it. However,\n>in what follows I will use the phrase "the existence of God" in it\'s\n>\'usual sense\' - and this is the sense that I think you are using it.\n>I would like a clarification upon what you mean by "the existence of\n>God".\n>\n \nNo, that\'s a word game. The term god is used in a different way usually.\nWhen you use a different definition it is your thing, but until it is\ncommonly accepted you would have to say the way I define god is ... and\nthat does not exist, it is existence itself, so I say it does not exist.\n \nInterestingly, there are those who say that "existence exists" is one of\nthe indubitable statements possible.\n \nFurther, saying god is existence is either a waste of time, existence is\nalready used and there is no need to replace it by god, or you are implying\nmore with it, in which case your definition and your argument so far\nare incomplete, making it a fallacy.\n \n \n(Deletion)\n>One can never prove that God does or does not exist. When you say\n>that you believe God does not exist, and that this is an opinion\n>"based upon observation", I will have to ask "what observtions are\n>you refering to?" There are NO observations - pro or con - that\n>are valid here in establishing a POSITIVE belief.\n(Deletion)\n \nWhere does that follow? Aren\'t observations based on the assumption\nthat something exists?\n \nAnd wouldn\'t you say there is a level of definition that the assumption\n"god is" is meaningful. If not, I would reject that concept anyway.\n \nSo, where is your evidence for that "god is" is meaningful at some level?\n   Benedikt\n']
    transfer_test_data = None

    #   请在此添加实现代码   #
    # ********** Begin *********#
    v= TfidfVectorizer (min_df=2,stop_words="english")
    jxh=v.fit_transform(X)
    transfer_test_data=v.transform(test_data).toarray()


    # ********** End **********#

    return transfer_test_data

第4关:使用scikit-learn分类器SVM对digits数据分类

import matplotlib.pyplot as plt

# 导入数据集,分类器相关包
from sklearn import datasets, svm, metrics

# 导入digits数据集
digits = datasets.load_digits()
n_samples = len(digits.data)
data = digits.data

# 使用前一半的数据集作为训练数据,后一半数据集作为测试数据
train_data,train_target = data[:n_samples // 2],digits.target[:n_samples // 2]
test_data,test_target = data[n_samples // 2:],digits.target[n_samples // 2:]


def createModelandPredict():
    '''
    创建分类模型并对测试数据预测

    返回值:
    predicted - 测试数据预测分类值
    '''
    predicted = None
    #   请在此添加实现代码   #
    #********** Begin *********#
    classifier=svm.SVC()
    classifier.fit(train_data,train_target)
    predicted=classifier.predict(test_data)
 
    
    #********** End **********#

    return predicted

第5关:模型持久化

# 导入数据集,分类器相关包
from sklearn import datasets, svm, metrics
import pickle

# 导入digits数据集
digits = datasets.load_digits()
n_samples = len(digits.data)
data = digits.data

# 使用前一半的数据集作为训练数据,后一半数据集作为测试数据
train_data,train_target = data[:n_samples // 2],digits.target[:n_samples // 2]
test_data,test_target = data[n_samples // 2:],digits.target[n_samples // 2:]


def createModel():
    classifier = svm.SVC()
    classifier.fit(train_data,train_target)
    return classifier

local_file = 'dumpfile'
def dumpModel():
    '''
    存储分类模型

    '''
    clf = createModel()
    # 请在此处补全模型存储语句 #
    #********** Begin *********#
    f_model = open(local_file,'wb')
    pickle.dump(clf,f_model)
    #********** End **********#

def loadModel():
    '''
    加载模型,并使用模型对测试数据进行预测,返回预测值

    返回值:
    predicted - 模型预测值
    '''
    predicted = None
    # 请在此处补全模型加载语句,并对预测数据分类返回预测值#
    #********** Begin *********#
    fw = open(local_file,'rb')
    classifier = pickle.loads(fw.read())
    predicted = classifier.predict(test_data)
    #********** End **********#

    return predicted



第6关:模型评估-量化预测效果

from sklearn.metrics import accuracy_score,precision_score,f1_score,precision_recall_fscore_support
from sklearn.svm import LinearSVC,SVC
def bin_evaluation(X_train, y_train, X_test, y_test):
    '''
    评估二分类模型
    :param X_train: 训练数据集
    :param y_train: 训练集类别
    :param X_test: 测试数据集
    :param y_test: 测试集实际类别
    :return:
    correct_num - 正确分类的样本个数
    prec - 正类的准确率
    recall - 正类的召回率
    f_score - 正类的f值
    '''
    classifier = LinearSVC()
    correct_num, prec, recall, fscore = None, None, None, None
    #   请在此添加实现代码   #
    # ********** Begin *********#
    classifier.fit(X_train, y_train)
    y_pred = classifier.predict(X_test)

    correct_num = accuracy_score(y_test, y_pred, normalize=False)
    prec, recall, fscore, support = precision_recall_fscore_support(y_test, y_pred, average="binary", pos_label=1)

    return correct_num, prec, recall, fscore




    # ********** End **********#
def multi_evaluation(X_train,y_train,X_test,y_test):
    '''
    评估多分类模型
    :param X_train: 训练数据集
    :param y_train: 训练集类别
    :param X_test: 测试数据集
    :param y_test: 测试集实际类别
    :return:
    acc - 模型的精度
    prec - 准确率
    f_score - f值
    '''
    #初始化
    acc,prec,f_score = None,None,None
    classifier = SVC(kernel='linear')
    #   请在此添加实现代码   #
    # ********** Begin *********#
    classifier.fit(X_train, y_train)
    y_pred = classifier.predict(X_test)

    acc = accuracy_score(y_test, y_pred)
    prec, zhaohui, f_score, sp_score = precision_recall_fscore_support(y_test, y_pred, average='macro')

    return acc,prec,f_score



    # ********** End **********#

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shining0596

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值