利用Sklearn中的逻辑回归(LogisticRegression)对手写数字(load_digits) ...

打印 上一主题 下一主题

主题 852|帖子 852|积分 2558

一、数据集分析

该手写数据为Sklearn内置数据集,导入数据集:
  1. from sklearn.datasets import load_digits
复制代码
1.1 数据集规格 



  • 1797个样本,每个样本包括8*8像素的图像和一个[0, 9]整数的标签
  • 数据集data中,每一个样本均有64个数据位float64型。
  • 关于手写数字识别标题:通过练习一个8x8 的手写数字图片中每个像素点差别的灰度值,来判断数字,是一个分类标题.
内置文件来自作者的解说:
  1.     """Load and return the digits dataset (classification).
  2.     Each datapoint is a 8x8 image of a digit.
  3.     =================   ==============
  4.     Classes                         10
  5.     Samples per class             ~180
  6.     Samples total                 1797
  7.     Dimensionality                  64
  8.     Features             integers 0-16
  9.     =================   ==============
  10.     This is a copy of the test set of the UCI ML hand-written digits datasets
  11.     https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits
  12.     Read more in the :ref:`User Guide <digits_dataset>`.
  13.     Parameters
  14.     ----------
  15.     n_class : int, default=10
  16.         The number of classes to return. Between 0 and 10.
  17.     return_X_y : bool, default=False
  18.         If True, returns ``(data, target)`` instead of a Bunch object.
  19.         See below for more information about the `data` and `target` object.
  20.         .. versionadded:: 0.18
  21.     as_frame : bool, default=False
  22.         If True, the data is a pandas DataFrame including columns with
  23.         appropriate dtypes (numeric). The target is
  24.         a pandas DataFrame or Series depending on the number of target columns.
  25.         If `return_X_y` is True, then (`data`, `target`) will be pandas
  26.         DataFrames or Series as described below.
  27.         .. versionadded:: 0.23
  28.     Returns
  29.     -------
  30.     data : :class:`~sklearn.utils.Bunch`
  31.         Dictionary-like object, with the following attributes.
  32.         data : {ndarray, dataframe} of shape (1797, 64)
  33.             The flattened data matrix. If `as_frame=True`, `data` will be
  34.             a pandas DataFrame.
  35.         target: {ndarray, Series} of shape (1797,)
  36.             The classification target. If `as_frame=True`, `target` will be
  37.             a pandas Series.
  38.         feature_names: list
  39.             The names of the dataset columns.
  40.         target_names: list
  41.             The names of target classes.
  42.             .. versionadded:: 0.20
  43.         frame: DataFrame of shape (1797, 65)
  44.             Only present when `as_frame=True`. DataFrame with `data` and
  45.             `target`.
  46.             .. versionadded:: 0.23
  47.         images: {ndarray} of shape (1797, 8, 8)
  48.             The raw image data.
  49.         DESCR: str
  50.             The full description of the dataset.
  51.     (data, target) : tuple if ``return_X_y`` is True
  52.         A tuple of two ndarrays by default. The first contains a 2D ndarray of
  53.         shape (1797, 64) with each row representing one sample and each column
  54.         representing the features. The second ndarray of shape (1797) contains
  55.         the target samples.  If `as_frame=True`, both arrays are pandas objects,
  56.         i.e. `X` a dataframe and `y` a series.
  57.         .. versionadded:: 0.18
  58.     Examples
  59.     --------
  60.     To load the data and visualize the images::
  61.         >>> from sklearn.datasets import load_digits
  62.         >>> digits = load_digits()
  63.         >>> print(digits.data.shape)
  64.         (1797, 64)
  65.         >>> import matplotlib.pyplot as plt
  66.         >>> plt.gray()
  67.         >>> plt.matshow(digits.images[0])
  68.         <...>
  69.         >>> plt.show()
  70.     """
复制代码
翻译(翻译的一言难尽,将就一下吧
): 
   “”“加载并返回数字数据集(分类)。每个数据点都是一个数字的 8x8 图像。 ==============类 每类 10 个样本 ~180 个样本 共 1797 维 64 特征 整数 0-16  ============== 这是 UCI ML 手写数字数据集测试集的副本 https:archive.ics.uci.edumldatasetsOptical+Recognition+of+Handwritten+Digits
  在 :ref:'用户指南<digits_dataset>中阅读更多内容'.参数 ----------
          n_class : int, default=10 要返回的类数。介于 0 和 10 之间。
          return_X_y : bool, default=False 如果为 True,则返回 ''(data, target)'' 而不是 Bunch 对象。有关“data”和“target”对象的具体信息,请参阅下文。
          as_frame : bool, default=False ,如果为 True,则数据是 pandas DataFrame,其中包含具有适当 dtypes (numeric) 的列。目标是 pandas DataFrame 或 Series,具体取决于目标列的数目。如果 'return_X_y' 为 True,则 ('data', 'target') 将是 pandas DataFrames 或 Series,如下所述。
  返回-------数据: :class:'~sklearn.utils.Bunch' 类似字典的对象,具有以下属性。
          data : {ndarray, dataframe} of shape (1797, 64) 扁平化的数据矩阵。如果 'as_frame=True',则 'data' 将是一个 pandas DataFrame。
          target: {ndarray, Series} of shape (1797,) 分类目标。如果 'as_frame=True',则 'target' 将是pandas  Series。
          feature_names:list 数据集列的名称。
          target_names:列出目标类的名称。
          frame: shape(1797, 65)的DataFrame,仅当'as_frame=True'时才出现。带有“data”和“target”的 DataFrame。
          images: {ndarray} of shape (1797, 8, 8) 原始图像数据。
          DESCR: str 数据集的完整形貌。
          (data, target) : tuple if ''return_X_y'' is True 默认环境下,两个 ndarrays 的元组。第一个包含外形 (1797, 64) 的 2D ndarray,每行代表一个样本,每列代表特征。外形 (1797) 的第二个 ndarray 包含目标样本。如果 'as_frame=True',则两个数组都是 pandas 对象,即 'X' 是数据帧,“y”是序列
   1.2 加载数据

  1. # 获取数据集数据和标签
  2. datas = load_digits()
  3. X_data = datas.data
  4. y_data = datas.target
复制代码
 1.3 展示数据集中前十个数据

代码:
  1. from matplotlib import pyplot as plt
  2. #  展示前十个数据的图像
  3. fig, ax = plt.subplots(
  4.     nrows=2,
  5.     ncols=5,
  6.     sharex=True,
  7.     sharey=True, )
  8. ax = ax.flatten()
  9. for i in range(10):
  10.     ax[i].imshow(datas.data[i].reshape((8, 8)), cmap='Greys', interpolation='nearest')
  11. plt.show()
复制代码
图像:

二、数据处理

2.1 划分数据集

  1. # 划分数据集
  2. X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.3)
复制代码
 三、建立模子

3.1 逻辑回归

3.1.1 LogisticRegression()重要参数

              penalty:指定正则化的参数可选为   "l1", “l2”    默以为   “l2”.    注意:   l1   正则化会将部分参        数压缩到   0   ,而   l2   正则化不会让参数取到   0   只会无线接近                C:大于   0   的浮点数。   C   越小对损失函数的惩罚越重                multi_class:告知模子要处理的分类标题是二分类还是多分类。 默以为   “ovr”   (二分类)    “multinational”:   表示处理多分类标题,在solver="liblinear"   时不可用    “auto”    : 表示让模子主动判断分类类型                solver:指定求解方式      3.2 建立逻辑回归模子

  1. # 建立逻辑回归模型
  2. model = LogisticRegression(max_iter=10000, random_state=42, multi_class='multinomial')
  3. # 训练模型
  4. model.fit(X_train, y_train)
复制代码
四、模子评估

  4.1 十折交叉验证

             十折交叉验证是将练习集分割成10个子样本,一个单独的子样本被保留作为验证模子的数据,其他9个样本用来练习。交叉验证重复10次,每个子样本验证一次,平均10次的效果或者利用其它结合方式,最终得到一个单一估测。这个方法的优势在于,同时重复运用随机产生的子样本举行练习和验证,每次的效果验证一次,10次交叉验证是最常用的。
   
  1. scores = cross_val_score(model, X_train, y_train, cv=10)  # 十折交叉验证
  2. k = 0
  3. for i in scores:
  4.     k += i
  5. print("十折交叉验证平均值:", k / 10)
  6. print(f"十折交叉验证:{scores}\n")
复制代码
效果:
  

  4.2 错误率

  1. y_pred = model.predict(X_test)
  2. error_rate = model.score(X_test, y_test)
  3. print(f"错误率:{error_rate}\n")
  4. print(f"测试集预测值:{y_pred}\n")
复制代码
效果:
  

  五、源码

  1. from sklearn.linear_model import LogisticRegressionfrom sklearn.datasets import load_digitsfrom sklearn.model_selection import cross_val_score, train_test_splitfrom matplotlib import pyplot as plt# 获取数据集数据和标签
  2. datas = load_digits()
  3. X_data = datas.data
  4. y_data = datas.target#  展示前十个数据的图像fig, ax = plt.subplots(    nrows=2,    ncols=5,    sharex=True,    sharey=True, )ax = ax.flatten()for i in range(10):    ax[i].imshow(datas.data[i].reshape((8, 8)), cmap='Greys', interpolation='nearest')plt.show()# 划分数据集
  5. X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.3)# 建立逻辑回归模子model = LogisticRegression(max_iter=10000, random_state=42, multi_class='multinomial')scores = cross_val_score(model, X_train, y_train, cv=10)  # 十折交叉验证k = 0for i in scores:    k += iprint("十折交叉验证平均值:", k / 10)model.fit(X_train, y_train)y_pred = model.predict(X_test)error_rate = model.score(X_test, y_test)print(f"十折交叉验证:{scores}\n")print(f"错误率:{error_rate}\n")print(f"测试集猜测值:{y_pred}\n")
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

拉不拉稀肚拉稀

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表