2025-1-28-sklearn学习(47) (48) 万家灯火亮年至,一声烟花开新来。
文章目录
- sklearn学习(47) & (48)
- sklearn学习(47) 把它们放在一起
- 47.1 模型管道化
- 47.2 用特征面进行人脸识别
- 47.3 开放性问题: 股票市场结构
- sklearn学习(48) 寻求帮助
- 48.1 项目邮件列表
- 48.2 机器学习从业者的 Q&A 社区
sklearn学习(47) & (48)
文章参考网站:
https://sklearn.apachecn.org/
和
https://scikit-learn.org/stable/
sklearn学习(47) 把它们放在一起
47.1 模型管道化
我们已经知道一些模型可以做数据转换,一些模型可以用来预测变量。我们可以建立一个组合模型同时完成以上工作:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pdfrom sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.linear_model import SGDClassifier
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV# Define a pipeline to search for the best combination of PCA truncation
# and classifier regularization.
logistic = SGDClassifier(loss='log', penalty='l2', early_stopping=True,max_iter=10000, tol=1e-5, random_state=0)
pca = PCA()
pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)])digits = datasets.load_digits()
X_digits = digits.data
y_digits = digits.target# Parameters of pipelines can be set using ‘__’ separated parameter names:
param_grid = {'pca__n_components': [5, 20, 30, 40, 50, 64],'logistic__alpha': np.logspace(-4, 4, 5),
}
search = GridSearchCV(pipe, param_grid, iid=False, cv=5)
search.fit(X_digits, y_digits)
print("Best parameter (CV score=%0.3f):" % search.best_score_)
print(search.best_params_)# Plot the PCA spectrum
pca.fit(X_digits)fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, figsize=(6, 6))
ax0.plot(pca.explained_variance_ratio_, linewidth=2)
ax0.set_ylabel('PCA explained variance')ax0.axvline(search.best_estimator_.named_steps['pca'].n_components,linestyle=':', label='n_components chosen')
47.2 用特征面进行人脸识别
该实例用到的数据集来自 LFW_(Labeled Faces in the Wild)。数据已经进行了初步预处理
http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB)
"""
===================================================
Faces recognition example using eigenfaces and SVMs
===================================================The dataset used in this example is a preprocessed excerpt of the
"Labeled Faces in the Wild", aka LFW_:http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB).. _LFW: http://vis-www.cs.umass.edu/lfw/Expected results for the top 5 most represented people in the dataset:================== ============ ======= ========== =======precision recall f1-score support
================== ============ ======= ========== =======Ariel Sharon 0.67 0.92 0.77 13Colin Powell 0.75 0.78 0.76 60Donald Rumsfeld 0.78 0.67 0.72 27George W Bush 0.86 0.86 0.86 146
Gerhard Schroeder 0.76 0.76 0.76 25Hugo Chavez 0.67 0.67 0.67 15Tony Blair 0.81 0.69 0.75 36avg / total 0.80 0.80 0.80 322
================== ============ ======= ========== ======="""
from time import time
import logging
import matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVCprint(__doc__)# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')# #############################################################################
# Download the data, if not already on disk and load it as numpy arrayslfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)# #############################################################################
# Split into a training set and a test set using a stratified k fold# split into a training and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)# #############################################################################
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
n_components = 150print("Extracting the top %d eigenfaces from %d faces"% (n_components, X_train.shape[0]))
t0 = time()
pca = PCA(n_components=n_components, svd_solver='randomized',whiten=True).fit(X_train)
print("done in %0.3fs" % (time() - t0))eigenfaces = pca.components_.reshape((n_components, h, w))print("Projecting the input data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))# #############################################################################
# Train a SVM classification modelprint("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'),param_grid, cv=5, iid=False)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)# #############################################################################
# Quantitative evaluation of the model quality on the test setprint("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done in %0.3fs" % (time() - t0))print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))# #############################################################################
# Qualitative evaluation of the predictions using matplotlibdef plot_gallery(images, titles, h, w, n_row=3, n_col=4):"""Helper function to plot a gallery of portraits"""plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)for i in range(n_row * n_col):plt.subplot(n_row, n_col, i + 1)plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)plt.title(titles[i], size=12)plt.xticks(())plt.yticks(())# plot the result of the prediction on a portion of the test setdef title(y_pred, y_test, target_names, i):pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]return 'predicted: %s\ntrue: %s' % (pred_name, true_name)prediction_titles = [title(y_pred, y_test, target_names, i)for i in range(y_pred.shape[0])]plot_gallery(X_test, prediction_titles, h, w)# plot the gallery of the most significative eigenfaceseigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)plt.show()
![]() | ![]() |
|---|---|
| Prediction | Eigenfaces |
数据集中前5名最有代表性样本的预期结果:
precision recall f1-score supportGerhard_Schroeder 0.91 0.75 0.82 28Donald_Rumsfeld 0.84 0.82 0.83 33Tony_Blair 0.65 0.82 0.73 34Colin_Powell 0.78 0.88 0.83 58George_W_Bush 0.93 0.86 0.90 129avg / total 0.86 0.84 0.85 282
47.3 开放性问题: 股票市场结构
我们可以预测 Google 在特定时间段内的股价变动吗?
Learning a graph structure
sklearn学习(48) 寻求帮助
48.1 项目邮件列表
如果您在使用 scikit 的过程中发现错误或者需要在说明文档中澄清的内容,可以随时通过 Mailing List 进行咨询。
48.2 机器学习从业者的 Q&A 社区
| Quora.com: | Quora有一个和机器学习问题相关的主题以及一些有趣的讨论: https://www.quora.com/topic/Machine-Learning |
|---|---|
| Stack Exchange: | Stack Exchange 系列网站包含 multiple subdomains for Machine Learning questions(机器学习问题的多个分支)_。 |
- ’斯坦福大学教授 Andrew Ng 教授的机器学习优秀免费在线课程’: https://www.coursera.org/learn/machine-learning
- ’另一个优秀的免费在线课程,对人工智能采取更一般的方法’: https://www.udacity.com/course/intro-to-artificial-intelligence–cs271
相关文章:
2025-1-28-sklearn学习(47) (48) 万家灯火亮年至,一声烟花开新来。
文章目录 sklearn学习(47) & (48)sklearn学习(47) 把它们放在一起47.1 模型管道化47.2 用特征面进行人脸识别47.3 开放性问题: 股票市场结构 sklearn学习(48) 寻求帮助48.1 项目邮件列表48.2 机器学习从业者的 Q&A 社区 sklearn学习(47) & (48) 文章参考网站&…...
Flask数据的增删改查(CRUD)_flask删除数据自动更新
查询年龄小于17的学生信息 Student.query.filter(Student.s_age < 17) students Student.query.filter(Student.s_age.__lt__(17))模糊查询,使用like,查询姓名中第二位为花的学生信息 like ‘_花%’,_代表必须有一个数据,%任何数据 st…...
算法随笔_33: 132模式
上一篇:算法随笔_32: 移掉k位数字-CSDN博客 题目描述如下: 给你一个整数数组 nums ,数组中共有 n 个整数。132 模式的子序列 由三个整数 nums[i]、nums[j] 和 nums[k] 组成,并同时满足:i < j < k 和 nums[i] < nums[k] < nums[j…...
Linux内核中的页面错误处理机制与按需分页技术
在现代操作系统中,内存管理是核心功能之一,而页面错误(Page Fault)处理机制是内存管理的重要组成部分。当程序访问一个尚未映射到物理内存的虚拟地址时,CPU会触发页面错误异常,内核需要捕获并处理这种异常,以决定如何响应,例如加载缺失的页面、处理权限错误等。Linux内…...
【Git】使用笔记总结
目录 概述安装Git注册GitHub配置Git常用命令常见场景1. 修改文件2. 版本回退3. 分支管理 常见问题1. git add [中文文件夹] 无法显示中文问题2. git add [文件夹] 文件名中含有空格3. git add 触发 LF 回车换行警告4. git push 提示不存在 Origin 仓库5. Git与GitHub中默认分支…...
C语言中的存储类
C语言中的存储类 在C语言中,存储类是用于定义变量和函数的作用域、生命周期以及可见性的关键字。存储类决定了数据在内存中的存储位置以及它们在程序中的使用方式。本文将详细介绍C语言中的存储类,包括其类型、作用以及如何使用。 1. 存储类的类型 C语…...
DeepSeek 云端部署,释放无限 AI 潜力!
1.简介 目前,OpenAI、Anthropic、Google 等公司的大型语言模型(LLM)已广泛应用于商业和私人领域。自 ChatGPT 推出以来,与 AI 的对话变得司空见惯,对我而言没有 LLM 几乎无法工作。 国产模型「DeepSeek-R1」的性能与…...
【Qt5】声明之后快速跳转
我在网上看到的方法是ctrlL(?不是很清楚,因为我跳转不成功!) 另外一种就是鼠标点击跳转的。 首先,声明私有成员函数 此时,一般步骤应该是在构造函数里面继续,写函数的框架什么的。于…...
flowable expression和json字符串中的双引号内容
前言 最近做项目,发现了一批特殊的数据,即特殊字符",本身输入双引号也不是什么特殊的字符,毕竟在存储时就是正常字符,只不过在编码的时候需要转义,转义符是\,然而转义符\也是特殊字符&…...
新一代搜索引擎,是 ES 的15倍?
Manticore Search介绍 Manticore Search 是一个使用 C 开发的高性能搜索引擎,创建于 2017 年,其前身是 Sphinx Search 。Manticore Search 充分利用了 Sphinx,显着改进了它的功能,修复了数百个错误,几乎完全重写了代码…...
Pandas基础06(异常值的检测与过滤/抽样/常用聚合函数/数据聚合)
Pandas基础06 异常值的检测与过滤 在数据分析中,异常值(Outliers)是指与其他数据点显著不同的值。这些值可能由于数据录入错误、设备故障或极端情况而产生,因此在进行数据分析之前,需要对其进行检测与过滤。本文将介绍…...
事务01之事务机制
事务机制 文章目录 事务机制一:ACID1:什么是ACID2:MySQL是如何实现ACID的 二:MySQL事务机制综述1:手动管理事务2:事务回滚点3:事务问题和隔离机制(面试)3.1:事…...
Python-基于mediapipe,pyautogui,cv2和numpy的电脑手势截屏工具(进阶版)
前言:在我们的日常生活中,手机已经成为我们每天工作,学习,生活的一个不可或缺的部分。众所周知:为了我们的使用方便,手机里面的很多功能非常人性化,既便捷又高效,其中就有手机的截屏方式,它们花样繁多,如三指截屏,手势截屏等。那么怎么在电脑里面也实现这个功能呢?…...
@EventListener底层原理(超详细)| @TransactionalEventListener底层原理 | 事务同步
0. 举个栗子0.1. 事件监听方法0.2. 事件推送 1. EventListener注解2. EventListener标注的监听方法解析2.1. 事件监听方法处理器EventListenerMethodProcessors2.1.1. AbstractApplicationContext.invokeBeanFactoryPostProcessors2.1.2. AbstractApplicationContext.initAppli…...
NX/UG二次开发—CAM—快速查找程序参数名称
使用UF_PARAM_XXX读取或设置参数时,会发现程序中有一个INT类型参数param_index,这个就是对应程序中的参数,比如读取程序余量,则param_index = UF_PARAM_STOCK_PART,读取程序的加工坐标系则param_index = UF_PARAM_MCS等等。 你需要读取什么参数,只要只能在uf_param_indic…...
X86路由搭配rtl8367s交换机
x86软路由,买双网口就好。或者单网口主板,外加一个pcie千兆。 华硕h81主板戴尔i350-T2双千兆,做bridge下载,速度忽高忽低。 今天交换机到货,poe供电,还是网管,支持Qvlan及IGMP Snooping…...
【C++语言】卡码网语言基础课系列----5. A+B问题VIII
文章目录 练习题目AB问题VIII具体代码实现 小白寄语诗词共勉 练习题目 AB问题VIII 题目描述: 你的任务是计算若干整数的和。 输入描述: 输入的第一行为一个整数N,接下来N行每行先输入一个整数M,然后在同一行内输入M个整数。 输出…...
【LLM-agent】(task1)简单客服和阅卷智能体
note 一个完整的agent有模型 (Model)、工具 (Tools)、编排层 (Orchestration Layer)一个好的结构化 Prompt 模板,某种意义上是构建了一个好的全局思维链。 如 LangGPT 中展示的模板设计时就考虑了如下思维链:Role (角色) -> Profile(角色…...
CAP 定理的 P 是什么
分布式系统 CAP 定理 P 代表什么含义 作者之前在看 CAP 定理时抱有很大的疑惑,CAP 定理的定义是指在分布式系统中三者只能满足其二,也就是存在分布式 CA 系统的。作者在网络上查阅了很多关于 CAP 文章,虽然这些文章对于 P 的解释五花八门&am…...
RK3568使用opencv(使用摄像头捕获图像数据显示)
文章目录 一、opencv相关的类1. **cv::VideoCapture**2. **cv::Mat**3. **cv::cvtColor**4. **QImage**5. **QPixmap**总结二、代码实现一、opencv相关的类 1. cv::VideoCapture cv::VideoCapture 是 OpenCV 中用于视频捕捉的类,常用于从摄像头、视频文件、或者图像序列中捕…...
ZZNUOJ(C/C++)基础练习1021——1030(详解版)
目录 1021 : 三数求大值 C语言版 C版 代码逻辑解释 1022 : 三整数排序 C语言版 C版 代码逻辑解释 补充 (C语言版,三目运算)C类似 代码逻辑解释 1023 : 大小写转换 C语言版 C版 1024 : 计算字母序号 C语言版 C版 代码逻辑总结…...
2025 年,链上固定收益领域迈向新时代
“基于期限的债券市场崛起与 Secured Finance 的坚定承诺” 2025年,传统资产——尤其是股票和债券——大规模涌入区块链的浪潮将创造历史。BlackRock 首席执行官 Larry Fink 近期在彭博直播中表示,代币化股票和债券将逐步融入链上生态,将进一…...
使用where子句筛选记录
默认情况下,SearchCursor将返回一个表或要素类的所有行.然而在很多情况下,常常需要某些条件来限制返回行数. 操作方法: 1.打开IDLE,加载先前编写的SearchCursor.py脚本 2.添加where子句,更新SearchCursor()函数,查找记录中有<>文本的<>字段 with arcpy.da.Searc…...
基于互联网+智慧水务信息化整体解决方案
智慧水务的概述与发展背景 智慧水务是基于互联网、云计算、大数据、物联网等先进技术,对水务行业的工程建设、生产管理、管网运营、营销服务及企业综合管理等业务进行全面智慧化管理的创新模式。它旨在解决水务企业分散经营、管理水平不高、投资不足等问题。 水务…...
FIDL:Flutter与原生通讯的新姿势,不局限于基础数据类型
void initUser(User user); } 2、执行命令./gradlew assembleDebug,生成IUserServiceStub类和fidl.json文件 3、打开通道,向Flutter公开方法 FidlChannel.openChannel(getFlutterEngine().getDartExecutor(), new IUserServiceStub() { Override void…...
文件读写操作
写入文本文件 #include <iostream> #include <fstream>//ofstream类需要包含的头文件 using namespace std;void test01() {//1、包含头文件 fstream//2、创建流对象ofstream fout;/*3、指定打开方式:1.ios::out、ios::trunc 清除文件内容后打开2.ios:…...
cf1000(div.2)
Minimal Coprime最小公倍数 输入: 6 1 2 1 10 49 49 69 420 1 1 9982 44353 输出: 1 9 0 351 1 34371 代码...
【2025年数学建模美赛E题】(农业生态系统)完整解析+模型代码+论文
生态共生与数值模拟:生态系统模型的物种种群动态研究 摘要1Introduction1.1Problem Background1.2Restatement of the Problem1.3Our Work 2 Assumptions and Justifications3 Notations4 模型的建立与求解4.1 农业生态系统模型的建立与求解4.1.1 模型建立4.1.2求解…...
jhat命令详解
jhat 命令通常与 jmap 搭配使用,用来分析 jmap 生成的 dump 文件,jhat 内置了一个微型的HTTP/HTML服务器,生成 dump 的分析结果后,可以在浏览器中查看。 命令的使用格式如下。(其中heap-dump-file为必填项)…...
FFmpeg(7.1版本)的基本组成
1. 前言 FFmpeg 是一个非常流行的开源项目,它提供了处理音频、视频以及其他多媒体内容的强大工具。FFmpeg 包含了大量的库,可以用来解码、编码、转码、处理和播放几乎所有类型的多媒体文件。它广泛用于视频和音频的录制、转换、流媒体传输等领域。 2. FFmpeg的组成 1. FFmp…...

