机器学习1

机器学习的定义

机器学习是人工智能的一个分支,它使计算机系统能够从数据中学习和改进,而无需进行明确的编程。简单来说,机器学习涉及到开发算法和统计模型,这些模型可以帮助计算机使用样本数据(即训练数据)来做出预测或决策,而不需要针对所有可能的情况编写特定的指令。

机器学习的定义可以概括为以下几个要点:

  1. 数据驱动:机器学习模型依赖于大量的数据来学习模式和关系。
  2. 模式识别:机器学习算法能够识别数据中的模式,这些模式对于人类来说可能难以察觉。
  3. 预测和决策:机器学习可以用于预测未来事件或帮助做出决策。
  4. 自动化:机器学习可以自动化许多任务,特别是那些涉及大量数据的任务。
  5. 适应性:机器学习模型可以根据新数据进行调整和改进,从而适应新的情况。

机器学习可以分为几种类型,包括:

  • 监督学习(Supervised Learning):算法从标记的训练数据中学习,并预测未见过的数据的标签。
  • 无监督学习(Unsupervised Learning):算法从未标记的数据中学习,尝试找到数据中的结构和模式。
  • 半监督学习(Semi-supervised Learning):结合了监督学习和无监督学习的特点,使用少量标记数据和大量未标记数据。
  • 强化学习(Reinforcement Learning):算法通过与环境交互来学习如何做出决策,以最大化某种累积奖励。

scikit-learn工具介绍

Scikit-learn(简称sklearn)是一个基于Python的开源机器学习库,它建立在NumPy、SciPy、Pandas和Matplotlib等库之上,提供了简单高效的数据挖掘和数据分析工具。Scikit-learn涵盖了几乎所有主流的机器学习算法,包括分类、回归、聚类、降维等,并且它的API设计良好,接口简单,非常适合初学者上手 。

Scikit-learn的主要特点包括:

  1. 数据预处理:提供了丰富的数据预处理工具,如数据清洗、编码、标准化、特征提取和特征选择等。
  2. 机器学习算法:包括了各种常用的监督学习和无监督学习算法,例如支持向量机(SVM)、随机森林、逻辑回归等。
  3. 模型评估和选择:提供了一套完善的模型评估和选择工具,包括交叉验证、网格搜索和多种评估指标。
  4. 可视化工具:虽然Scikit-learn本身不提供绘图功能,但可以与matplotlib等Python绘图库配合使用,实现数据和模型效果的可视化。
  5. 内置数据集:提供了一些内置的数据集,如鸢尾花数据集(Iris dataset)和波士顿房价数据等,方便用户进行学习和测试。

数据集

一些常用的内置数据集:

  1. 鸢尾花数据集(Iris):

    • 特征:4个数值特征(花萼长度、花萼宽度、花瓣长度、花瓣宽度)。
    • 类别:3类(山鸢尾、变色鸢尾和维吉尼亚鸢尾)。
    • 用途:多类分类问题的入门数据集。
  2. 手写数字数据集(Digits):

    • 特征:8x8像素的灰度图像,共64个特征。
    • 类别:10类(0到9的数字)。
    • 用途:多类分类,特别是图像识别和手写识别。
  3. 葡萄酒数据集(Wine):

    • 特征:13个化学属性,如酒精含量、灰分等。
    • 类别:3类葡萄酒品种。
    • 用途:多类分类,化学成分分析。
  4. 乳腺癌数据集(Breast Cancer):

    • 特征:30个特征,包括细胞大小、形状等。
    • 类别:2类(良性和恶性)。
    • 用途:二元分类,医学诊断。
  5. 加州住房数据集(California Housing):

    • 特征:8个特征,包括房屋的中位收入、年龄、房间数等。
    • 目标变量:房屋价格的中位数。
    • 用途:回归任务,房价预测。
  6. 波士顿房价数据集(Boston Housing):

    • 特征:13个特征,如犯罪率、地方财产税率等。
    • 目标变量:房屋价格。
    • 用途:回归任务,房价预测。
  7. 新闻组数据集(20 Newsgroups):

    • 特征:文本数据,包括不同的新闻组文章。
    • 类别:20类新闻组主题。
    • 用途:文本分类,主题识别。
  8. 糖尿病数据集(Diabetes Dataset):

    • 包含442个糖尿病患者的10个基线变量,如年龄、性别、体质指数等,以及一年后疾病进展的定量指标。
    • 数据集中的每个特征变量都已均值中心化,并按标准差乘以n_samples的平方根进行了缩放 92。

简单的数据集操作:

from sklearn.datasets import load_iris
iris = load_iris()
print(iris)
'''
运行结果:
{'data': array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
               ...
       [6.2, 3.4, 5.4, 2.3],
       [5.9, 3. , 5.1, 1.8]]), 'target': array([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]), 'frame': None, 'target_names': array(['setosa', 'versicolor', 'virginica'], dtype='<U10'), 'DESCR': '.. _iris_dataset:\n\nIris plants dataset\n--------------------\n\n**Data Set Characteristics:**\n\n    :Number of Instances: 150 (50 in each of three classes)\n    :Number of Attributes: 4 numeric, predictive attributes and the class\n    :Attribute Information:\n        - sepal length in cm\n        - sepal width in cm\n        - petal length in cm\n        - petal width in cm\n        - class:\n                - Iris-Setosa\n                - Iris-Versicolour\n                - Iris-Virginica\n                \n    :Summary Statistics:\n\n    ============== ==== ==== ======= ===== ====================\n                    Min  Max   Mean    SD   Class Correlation\n    ============== ==== ==== ======= ===== ====================\n    sepal length:   4.3  7.9   5.84   0.83    0.7826\n    sepal width:    2.0  4.4   3.05   0.43   -0.4194\n    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\n    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)\n    ============== ==== ==== ======= ===== ====================\n\n    :Missing Attribute Values: None\n    :Class Distribution: 33.3% for each of 3 classes.\n    :Creator: R.A. Fisher\n    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\n    :Date: July, 1988\n\nThe famous Iris database, first used by Sir R.A. Fisher. The dataset is taken\nfrom Fisher\'s paper. Note that it\'s the same as in R, but not as in the UCI\nMachine Learning Repository, which has two wrong data points.\n\nThis is perhaps the best known database to be found in the\npattern recognition literature.  Fisher\'s paper is a classic in the field and\nis referenced frequently to this day.  (See Duda & Hart, for example.)  The\ndata set contains 3 classes of 50 instances each, where each class refers to a\ntype of iris plant.  One class is linearly separable from the other 2; the\nlatter are NOT linearly separable from each other.\n\n.. topic:: References\n\n   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"\n     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to\n     Mathematical Statistics" (John Wiley, NY, 1950).\n   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.\n     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\n   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System\n     Structure and Classification Rule for Recognition in Partially Exposed\n     Environments".  IEEE Transactions on Pattern Analysis and Machine\n     Intelligence, Vol. PAMI-2, No. 1, 67-71.\n   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions\n     on Information Theory, May 1972, 431-433.\n   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II\n     conceptual clustering system finds 3 classes in the data.\n   - Many, many more ...', 'feature_names': ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'], 'filename': 'iris.csv', 'data_module': 'sklearn.datasets.data'}
'''
# print(iris.data)#得到特征
# print(iris.feature_names) #特征描述
# print(iris.target) #目标形状
# print(iris.target_names)#目标描述
# print(iris.filename) #iris.csv 保存后的文件名
# print(iris.DESCR)#数据集的描述

import pandas as pd
import numpy as np
iris = load_iris()
feature = iris.data
target = iris.target
target.shape=(len(target), 1)
data = np.hstack([feature, target])
cols = iris.feature_names
cols.append("target")
print(cols)
pd.DataFrame(data,columns=cols)
'''
运行结果:
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)', 'target']

     sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                  5.1               3.5                1.4               0.2   
1                  4.9               3.0                1.4               0.2   
2                  4.7               3.2                1.3               0.2   
3                  4.6               3.1                1.5               0.2   
4                  5.0               3.6                1.4               0.2   
..                 ...               ...                ...               ...   
145                6.7               3.0                5.2               2.3   
146                6.3               2.5                5.0               1.9   
147                6.5               3.0                5.2               2.0   
148                6.2               3.4                5.4               2.3   
149                5.9               3.0                5.1               1.8   

     target  
0       0.0  
1       0.0  
2       0.0  
3       0.0  
4       0.0  
..      ...  
145     2.0  
146     2.0  
147     2.0  
148     2.0  
149     2.0  

[150 rows x 5 columns]
'''
from sklearn.datasets import load_diabetes
diabetes = load_diabetes()
print(len(diabetes))
'''
运行结果:
8
'''
from sklearn import datasets
datasets.get_data_home()
'''
运行结果:
'C:\\Users\\34456\\scikit_learn_data'
'''
from sklearn.datasets import fetch_20newsgroups
new = fetch_20newsgroups(data_home = "../src",subset='all')
print(len(new.data)) 
'''
运行结果:
18846
'''

数据集划分

sklearn.model_selection.train_test_split(*arrays, **options)

参数说明:

  • *arrays: 一个或多个数组或数据集,它们将被分割。这些可以是NumPy数组、Pandas数据框架、Scipy的稀疏矩阵或类似数组的对象。
  • **options: 一些可选参数,用于控制分割的方式。

常用可选参数:

  • test_size: 测试集占总数据的比例或数量。如果未指定,将使用默认值25%(即0.25)。
  • train_size: 训练集占总数据的比例或数量。如果指定了test_size,则不需要此参数。
  • random_state: 控制随机分割的随机状态。如果为整数,则作为随机数生成器的种子;如果为None,则每次分割的结果可能不同。
  • shuffle: 是否在分割前对数据进行洗牌。默认为True
  • stratify: 如果提供,将根据该参数的值进行分层抽样,以确保训练集和测试集中各类别的比例与原始数据集中相同。

返回值:

函数返回两个或多个数组,分别是训练集和测试集。如果输入了多个数组,将返回相同数量的数组,每个数组对应输入数组的一个分割版本。

from sklearn.model_selection import train_test_split

#列表数据集划分
data1 = [0, 1, 2, 3, 4, 5]
data2 = ["a", "1a", "2a", "3a", "4a", "5a"]
a, b = train_test_split(data1, test_size=0.2, random_state=2)
print(a, b)
a, b = train_test_split(data2, test_size=0.2, random_state=2)
print(a, b)
a, b, c, d = train_test_split(data1, data2, test_size=0.2, random_state=2)
print(a, b, c, d)
'''
运行结果:
[3, 2, 5, 0] [4, 1]
['3a', '2a', '5a', 'a'] ['4a', '1a']
[3, 2, 5, 0] [4, 1] ['3a', '2a', '5a', 'a'] ['4a', '1a']
'''
#ndarray数据集划分
import numpy as np

data3 = np.array([0, 1, 2, 3, 4, 5])
a, b, c, d = train_test_split(data1, data3, test_size=0.2, random_state=2)
print(a, b, c, d)
print(type(a), type(b), type(c), type(d))
'''
运行结果:
[3, 2, 5, 0] [4, 1] [3 2 5 0] [4 1]
<class 'list'> <class 'list'> <class 'numpy.ndarray'> <class 'numpy.ndarray'>
'''
#二维数组数据集划分
data4 = np.random.random((10, 3))
print(data4)
a, b = train_test_split(data4, test_size=0.2, random_state=0)
print(a, "\n", b)
'''
运行结果:
[[0.18918127 0.01049852 0.62876118]
 [0.74940388 0.19903339 0.24011533]
 [0.25313967 0.58917435 0.89608471]
 [0.36992016 0.49757658 0.96574899]
 [0.40341242 0.36875371 0.39340307]
 [0.80758224 0.7561119  0.39357163]
 [0.3376657  0.69533604 0.62902581]
 [0.03677359 0.24444224 0.40632209]
 [0.9359628  0.13824696 0.98525291]
 [0.75258568 0.23474756 0.01524074]]
[[0.40341242 0.36875371 0.39340307]
 [0.75258568 0.23474756 0.01524074]
 [0.74940388 0.19903339 0.24011533]
 [0.3376657  0.69533604 0.62902581]
 [0.03677359 0.24444224 0.40632209]
 [0.36992016 0.49757658 0.96574899]
 [0.18918127 0.01049852 0.62876118]
 [0.80758224 0.7561119  0.39357163]] 
 [[0.25313967 0.58917435 0.89608471]
 [0.9359628  0.13824696 0.98525291]]
'''
#DataFrame数据集划分
import pandas as pd

data5 = pd.DataFrame(data4)
print(data5)
a, b = train_test_split(data5, test_size=0.2, random_state=0)
print(a, "\n", b)
'''
运行结果:
          0         1         2
0  0.189181  0.010499  0.628761
1  0.749404  0.199033  0.240115
2  0.253140  0.589174  0.896085
3  0.369920  0.497577  0.965749
4  0.403412  0.368754  0.393403
5  0.807582  0.756112  0.393572
6  0.337666  0.695336  0.629026
7  0.036774  0.244442  0.406322
8  0.935963  0.138247  0.985253
9  0.752586  0.234748  0.015241
          0         1         2
4  0.403412  0.368754  0.393403
9  0.752586  0.234748  0.015241
1  0.749404  0.199033  0.240115
6  0.337666  0.695336  0.629026
7  0.036774  0.244442  0.406322
3  0.369920  0.497577  0.965749
0  0.189181  0.010499  0.628761
5  0.807582  0.756112  0.393572 
           0         1         2
2  0.253140  0.589174  0.896085
8  0.935963  0.138247  0.985253
'''
#字典数据集划分 
from sklearn.feature_extraction import DictVectorizer

data = [
    {'city': '成都', 'age': 30, 'temperature': 20},
    {'city': '重庆', 'age': 33, 'temperature': 60},
    {'city': '北京', 'age': 42, 'temperature': 80},
    {'city': '上海', 'age': 22, 'temperature': 70},
    {'city': '成都', 'age': 72, 'temperature': 40},
    {'city': '广州', 'age': 28, 'temperature': 30},
    {'city': '深圳', 'age': 35, 'temperature': 65},
    {'city': '杭州', 'age': 24, 'temperature': 55},
    {'city': '西安', 'age': 31, 'temperature': 45},
    {'city': '成都', 'age': 45, 'temperature': 35},
    {'city': '武汉', 'age': 29, 'temperature': 50},
    {'city': '南京', 'age': 36, 'temperature': 62},
    {'city': '长沙', 'age': 27, 'temperature': 72},
    {'city': '天津', 'age': 32, 'temperature': 48},
    {'city': '成都', 'age': 58, 'temperature': 42}
]
transfer = DictVectorizer(sparse=True)
data_new = transfer.fit_transform(data)
#print(data_new)
x = data_new.toarray()
print(x)
'''
运行结果:
[[30.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0. 20.]
 [33.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0. 60.]
 [42.  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0. 80.]
 [22.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0. 70.]
 [72.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0. 40.]
 [28.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0. 30.]
 [35.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0. 65.]
 [24.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0. 55.]
 [31.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0. 45.]
 [45.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0. 35.]
 [29.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0. 50.]
 [36.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0. 62.]
 [27.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1. 72.]
 [32.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.  0. 48.]
 [58.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0. 42.]]

'''
# 鸢尾花数据集划分
from sklearn.datasets import load_iris
iris = load_iris()
list = train_test_split(iris.data, iris.target, test_size=0.2, random_state=22)
x_train, x_test, y_train, y_test = list
print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)
'''
运行结果:
(120, 4) (30, 4) (120,) (30,)
'''
# 现实世界数据集划分
from sklearn.datasets import fetch_20newsgroups
new = fetch_20newsgroups(data_home = "../src",subset='all')
list1 = train_test_split(new.data, new.target, test_size=0.2, random_state=22)
x_train, x_test, y_train, y_test = list1
print(len(x_train), len(x_test), len(y_train), len(y_test))
'''
运行结果:
15076 3770 15076 3770
'''

作业:获取“加载加利福尼亚住房数据集”,并进行数据集划分

 

import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split

# 设置数据集的存储位置  
data_home = './CaliforniaHousing/'

# 加载加利福尼亚住房数据集  
housing = fetch_openml(name='housing', version=1, parser='auto', data_home=data_home)

# 将数据转换为 DataFrame  
housing_data = pd.DataFrame(housing.data, columns=housing.feature_names)

# 划分数据集为训练集和测试集  
X_train, X_test, y_train, y_test = train_test_split(housing_data, housing.target, test_size=0.2, random_state=42)

# 输出训练集和测试集的形状  
print("训练集特征形状:", X_train.shape)
print("测试集特征形状:", X_test.shape)
print("训练集目标形状:", y_train.shape)
print("测试集目标形状:", y_test.shape)
'''
运行结果:
训练集特征形状: (404, 6)
测试集特征形状: (102, 6)
训练集目标形状: (404, 6)
测试集目标形状: (102, 6)
'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值