【人工智能】Python在机器学习与人工智能中的应用

Python因其简洁易用、丰富的库支持以及强大的社区,被广泛应用于机器学习与人工智能(AI)领域。本教程通过实用的代码示例和讲解,带你从零开始掌握Python在机器学习与人工智能中的基本用法。


1. 机器学习与AI的Python生态系统

Python拥有多种支持机器学习和AI的库,以下是几个核心库:

  • NumPy:处理高效数组和矩阵运算。
  • Pandas:提供数据操作与分析工具。
  • Matplotlib/Seaborn:用于数据可视化。
  • Scikit-learn:机器学习的核心库,包含分类、回归、聚类等算法。
  • TensorFlow/PyTorch:深度学习框架,用于构建和训练神经网络。

安装:

pip install numpy pandas matplotlib scikit-learn tensorflow

2. 数据预处理

加载数据
import pandas as pd# 示例数据
data = pd.DataFrame({'Feature1': [1, 2, 3, 4, 5],'Feature2': [5, 4, 3, 2, 1],'Target': [1, 0, 1, 0, 1]
})print(data)

输出:

   Feature1  Feature2  Target
0         1         5       1
1         2         4       0
2         3         3       1
3         4         2       0
4         5         1       1
特征缩放

归一化或标准化数据有助于提升模型性能。

import pandas as pd
from sklearn.preprocessing import MinMaxScalerdata = pd.DataFrame({'Feature1': [1, 2, 3, 4, 5],'Feature2': [5, 4, 3, 2, 1],'Target': [1, 0, 1, 0, 1]
})scaler = MinMaxScaler()
scaled_features = scaler.fit_transform(data[['Feature1', 'Feature2']])
print(scaled_features)

输出:

[[0.   1.  ][0.25 0.75][0.5  0.5 ][0.75 0.25][1.   0.  ]]

3. 数据可视化

利用MatplotlibSeaborn绘制数据分布图。

import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import seaborn as snsdata = pd.DataFrame({'Feature1': [1, 2, 3, 4, 5],'Feature2': [5, 4, 3, 2, 1],'Target': [1, 0, 1, 0, 1]
})scaler = MinMaxScaler()
scaled_features = scaler.fit_transform(data[['Feature1', 'Feature2']])
print(scaled_features)# 散点图
sns.scatterplot(x='Feature1', y='Feature2', hue='Target', data=data)
plt.title('Feature Scatter Plot')
plt.show()


4. 构建第一个机器学习模型

使用Scikit-learn实现分类模型。

拆分数据
import pandas as pd
from sklearn.model_selection import train_test_splitdata = pd.DataFrame({'Feature1': [1, 2, 3, 4, 5],'Feature2': [5, 4, 3, 2, 1],'Target': [1, 0, 1, 0, 1]
})X = data[['Feature1', 'Feature2']]
y = data['Target']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)print('X_train:')
print(X_train)
print('X_test:')
print(X_test)
print('y_train:')
print(y_train)
print('y_test:')
print(y_test)
X_train:Feature1  Feature2
4         5         1
2         3         3
0         1         5
3         4         2X_test:Feature1  Feature2
1         2         4y_train:
4    1
2    1
0    1
3    0
Name: Target, dtype: int64y_test:
1    0
Name: Target, dtype: int64
训练模型
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_scoredata = pd.DataFrame({'Feature1': [1, 2, 3, 4, 5],'Feature2': [5, 4, 3, 2, 1],'Target': [1, 0, 1, 0, 1]
})X = data[['Feature1', 'Feature2']]
y = data['Target']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 随机森林分类器
model = RandomForestClassifier()
model.fit(X_train, y_train)# 预测
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
Accuracy: 0.0

5. 深度学习与神经网络

构建一个简单的神经网络进行分类任务。

安装TensorFlow
conda install tensorflow

如果安装遇到Could not solve for environment spec错误,请先执行以下命令

conda create -n tf_env python=3.8
conda activate tf_env   
构建模型
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense# 构建神经网络
model = Sequential([Dense(8, input_dim=2, activation='relu'),Dense(4, activation='relu'),Dense(1, activation='sigmoid')
])
编译与训练
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=1, verbose=1)
评估模型
loss, accuracy = model.evaluate(X_test, y_test)
print("Loss:", loss)
print("Accuracy:", accuracy)
完整代码
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Densedata = pd.DataFrame({'Feature1': [1, 2, 3, 4, 5],'Feature2': [5, 4, 3, 2, 1],'Target': [1, 0, 1, 0, 1]
})X = data[['Feature1', 'Feature2']]
y = data['Target']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 构建神经网络
model = Sequential([Dense(8, input_dim=2, activation='relu'),Dense(4, activation='relu'),Dense(1, activation='sigmoid')
])model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=1, verbose=1)loss, accuracy = model.evaluate(X_test, y_test)
print("Loss:", loss)
print("Accuracy:", accuracy)

输出:

Epoch 1/50
4/4 [==============================] - 1s 1ms/step - loss: 0.6867 - accuracy: 0.5000
Epoch 2/50
4/4 [==============================] - 0s 997us/step - loss: 0.6493 - accuracy: 0.5000
Epoch 3/50
4/4 [==============================] - 0s 997us/step - loss: 0.6183 - accuracy: 0.5000
Epoch 4/50
4/4 [==============================] - 0s 665us/step - loss: 0.5920 - accuracy: 0.5000
Epoch 5/50
4/4 [==============================] - 0s 1ms/step - loss: 0.5702 - accuracy: 0.5000
Epoch 6/50
4/4 [==============================] - 0s 997us/step - loss: 0.5612 - accuracy: 0.7500
Epoch 7/50
4/4 [==============================] - 0s 998us/step - loss: 0.5405 - accuracy: 0.7500
Epoch 8/50
4/4 [==============================] - 0s 665us/step - loss: 0.5223 - accuracy: 0.7500
Epoch 9/50
4/4 [==============================] - 0s 1ms/step - loss: 0.5047 - accuracy: 0.7500
Epoch 10/50
4/4 [==============================] - 0s 665us/step - loss: 0.4971 - accuracy: 0.7500
Epoch 11/50
4/4 [==============================] - 0s 997us/step - loss: 0.4846 - accuracy: 0.7500
Epoch 12/50
4/4 [==============================] - 0s 997us/step - loss: 0.4762 - accuracy: 0.7500
Epoch 13/50
4/4 [==============================] - 0s 665us/step - loss: 0.4753 - accuracy: 0.7500
Epoch 14/50
4/4 [==============================] - 0s 997us/step - loss: 0.4623 - accuracy: 1.0000
Epoch 15/50
4/4 [==============================] - 0s 998us/step - loss: 0.4563 - accuracy: 1.0000
Epoch 16/50
4/4 [==============================] - 0s 998us/step - loss: 0.4530 - accuracy: 1.0000
Epoch 17/50
4/4 [==============================] - 0s 997us/step - loss: 0.4469 - accuracy: 1.0000
Epoch 18/50
4/4 [==============================] - 0s 997us/step - loss: 0.4446 - accuracy: 0.7500
Epoch 19/50
4/4 [==============================] - 0s 665us/step - loss: 0.4385 - accuracy: 0.7500
Epoch 20/50
4/4 [==============================] - 0s 998us/step - loss: 0.4355 - accuracy: 0.7500
Epoch 21/50
4/4 [==============================] - 0s 997us/step - loss: 0.4349 - accuracy: 0.7500
Epoch 22/50
4/4 [==============================] - 0s 665us/step - loss: 0.4290 - accuracy: 0.7500
Epoch 23/50
4/4 [==============================] - 0s 997us/step - loss: 0.4270 - accuracy: 0.7500
Epoch 24/50
4/4 [==============================] - 0s 997us/step - loss: 0.4250 - accuracy: 0.7500
Epoch 25/50
4/4 [==============================] - 0s 665us/step - loss: 0.4218 - accuracy: 0.7500
Epoch 26/50
4/4 [==============================] - 0s 997us/step - loss: 0.4192 - accuracy: 0.7500
Epoch 27/50
4/4 [==============================] - 0s 997us/step - loss: 0.4184 - accuracy: 0.7500
Epoch 28/50
4/4 [==============================] - 0s 665us/step - loss: 0.4152 - accuracy: 0.7500
Epoch 29/50
4/4 [==============================] - 0s 997us/step - loss: 0.4129 - accuracy: 0.7500
Epoch 30/50
4/4 [==============================] - 0s 997us/step - loss: 0.4111 - accuracy: 0.7500
Epoch 31/50
4/4 [==============================] - 0s 997us/step - loss: 0.4095 - accuracy: 0.7500
Epoch 32/50
4/4 [==============================] - 0s 997us/step - loss: 0.4070 - accuracy: 0.7500
Epoch 33/50
4/4 [==============================] - 0s 997us/step - loss: 0.4053 - accuracy: 0.7500
Epoch 34/50
4/4 [==============================] - 0s 997us/step - loss: 0.4033 - accuracy: 0.7500
Epoch 35/50
4/4 [==============================] - 0s 998us/step - loss: 0.4028 - accuracy: 0.7500
Epoch 36/50
4/4 [==============================] - 0s 997us/step - loss: 0.3998 - accuracy: 0.7500
Epoch 37/50
4/4 [==============================] - 0s 1ms/step - loss: 0.3978 - accuracy: 0.7500
Epoch 38/50
4/4 [==============================] - 0s 997us/step - loss: 0.3966 - accuracy: 0.7500
Epoch 39/50
4/4 [==============================] - 0s 665us/step - loss: 0.3946 - accuracy: 0.7500
Epoch 40/50
4/4 [==============================] - 0s 997us/step - loss: 0.3926 - accuracy: 0.7500
Epoch 41/50
4/4 [==============================] - 0s 997us/step - loss: 0.3918 - accuracy: 0.7500
Epoch 42/50
4/4 [==============================] - 0s 997us/step - loss: 0.3898 - accuracy: 0.7500
Epoch 43/50
4/4 [==============================] - 0s 997us/step - loss: 0.3877 - accuracy: 0.7500
Epoch 44/50
4/4 [==============================] - 0s 997us/step - loss: 0.3861 - accuracy: 0.7500
Epoch 45/50
4/4 [==============================] - 0s 665us/step - loss: 0.3842 - accuracy: 0.7500
Epoch 46/50
4/4 [==============================] - 0s 665us/step - loss: 0.3830 - accuracy: 0.7500
Epoch 47/50
4/4 [==============================] - 0s 997us/step - loss: 0.3815 - accuracy: 0.7500
Epoch 48/50
4/4 [==============================] - 0s 665us/step - loss: 0.3790 - accuracy: 0.7500
Epoch 49/50
4/4 [==============================] - 0s 665us/step - loss: 0.3778 - accuracy: 0.7500
Epoch 50/50
4/4 [==============================] - 0s 997us/step - loss: 0.3768 - accuracy: 0.7500
1/1 [==============================] - 0s 277ms/step - loss: 2.8638 - accuracy: 0.0000e+00
Loss: 2.863826274871826
Accuracy: 0.0

6. 数据聚类

实现一个K-Means聚类模型:

from sklearn.cluster import KMeans# 数据
data_points = [[1, 2], [2, 3], [3, 4], [8, 7], [9, 8], [10, 9]]# K-Means
kmeans = KMeans(n_clusters=2)
kmeans.fit(data_points)# 输出聚类中心
print("Cluster Centers:", kmeans.cluster_centers_)

输出:

Cluster Centers: [[9. 8.][2. 3.]]

7. 自然语言处理 (NLP)

使用NLTK处理文本数据:

pip install nltk
文本分词
import nltknltk.download('punkt_tab')
nltk.download('punkt')from nltk.tokenize import word_tokenizetext = "Machine learning is amazing!"
tokens = word_tokenize(text)
print(tokens)

输出: 

['Machine', 'learning', 'is', 'amazing', '!']
词袋模型
from sklearn.feature_extraction.text import CountVectorizertexts = ["I love Python", "Python is great for AI"]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)print(X.toarray())

输出:  

[[0 0 0 0 1 1][1 1 1 1 0 1]]

8. 实用案例:房价预测

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error# 加载数据集
data = fetch_california_housing(as_frame=True)
X = data.data
y = data.target# 数据拆分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 模型训练
model = LinearRegression()
model.fit(X_train, y_train)# 预测
y_pred = model.predict(X_test)
print("Model Coefficients:", model.coef_)# 评估
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

输出:  

Model Coefficients: [ 4.48674910e-01  9.72425752e-03 -1.23323343e-01  7.83144907e-01-2.02962058e-06 -3.52631849e-03 -4.19792487e-01 -4.33708065e-01]
Mean Squared Error: 0.5558915986952442

总结

本教程涵盖了Python在机器学习和人工智能领域的基础应用,从数据预处理、可视化到模型构建和评估,再到深度学习的基本实现。通过这些示例,你可以逐步掌握如何使用Python进行机器学习和AI项目开发。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/61978.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

“iOS profile文件与私钥证书文件不匹配”总结打ipa包出现的问题

目录 文件和证书未加载或特殊字符问题 证书过期或Profile文件错误 确认开发者证书和私钥是否匹配 创建证书选择错误问题 申请苹果 AppId时勾选服务不全问题 ​总结 在上线ios平台的时候,在Hbuilder中打包遇见了问题,生成ipa文件时候,一…

element-ui 中el-calendar 日历插件获取显示的第一天和最后一天【原创】

需要获取el-calendar 日历组件上的第1天和最后一天。可以通过document.querySelector()方法进行获取dom元素中的值,这样避免计算问题。 获取的过程中主要有两个难点,第1个是处理上1月和下1月的数据,第2个是跨年的数据。 直接贴代码&#xff…

抓住鸿蒙生态崛起的机遇,拥抱未来开发挑战

随着华为鸿蒙(HarmonyOS)的持续发展,鸿蒙生态正在迅速崛起,逐步在智能手机、智能穿戴、车载、家居等领域形成完整闭环。它不仅为开发者带来了新的机遇,还带来了技术上的挑战。如何抓住这些机遇并应对挑战,是…

高标准农田智慧农业系统建设方案

1 项目概述 1.1 建设背景 我国是农业大国,近30年来农田高产量主要依靠农药化肥的大量投入,大部分化肥和水资源没有被有效利用而随地弃置,导致大量养分损失并造成环境污染。我国农业生产仍然以传统生产模式为主,传统耕种只能凭经验施肥灌溉,不仅浪费大量的人力物力,也对环…

基于Angular+BootStrap+SpringBoot简单的购物网站

目录 一、项目结构图 二、目录结构解析 后端 (Spring Boot) 前端 (Angular) 三、技术栈 四、具体功能实现 五、数据库设计 六、后端实现 1. 设置Spring Boot项目 2. 数据库实体类 3. 创建Repository 4. 创建Service层 5. 创建Controller层 七、前端实现&#xff0…

JavaScript的基础数据类型

一、JavaScript中的数组 定义 数组是一种特殊的对象,用于存储多个值。在JavaScript中,数组可以包含不同的数据类型,如数字、字符串、对象、甚至其他数组。数组的创建有两种常见方式: 字面量表示法:let fruits [apple…

5.5 W5500 TCP服务端与客户端

文章目录 1、TCP介绍2、W5500简介2.1 关键函数socketlistensendgetSn_RX_RSRrecv自动心跳包检测getSn_SR 1、TCP介绍 TCP 服务端: 创建套接字[socket]:服务器首先创建一个套接字,这是网络通信的端点。绑定套接字[bind]:服务器将…

PostGres命令【常用维护,增删改查】

文章目录 连接数据库列出数据库列出表增删改查操作基本的维护命令其他常用命令 PostgreSQL 中常用的 psql 命令,包括连接数据库、列出数据库、列出表、增删改查操作以及一些基本的维护命令。 连接数据库 启动 psql 客户端: psql -U your_username -d yo…

Android 15 版本更新及功能介绍

Android 15版本时间戳 Android 15,代号Vanilla Ice Cream(香草冰淇淋),是当下 Android 移动操作系统的最新主要版本。 开发者预览阶段:2024年2月,谷歌发布了Android 15的第一个开发者预览版本(DP1),这标志着新系统开发的正式启动。随后,在3月和4月,谷歌又相继推出了D…

第02章_MySQL环境搭建(基础)

1. MySQL 的卸载 1.1 步骤1:停止 MySQL 服务 在卸载之前,先停止 MySQL8.0 的服务。按键盘上的 “Ctrl Alt Delete” 组合键,打开“任务管理器”对话 框,可以在“服务”列表找到“MySQL8.0” 的服务,如果现在“正在…

Vue开发05:Vue中Ant-design主要控件用法demo(js为主)

Ant-design主要控件事件总结 在线测试网站:在线运行Vue组件 (rscl.cc) 以下demo全部基于ant-design-vue组件(版本1.7.8) 一、下拉框 1.选项直接赋值($event) 用下面这个技巧,可以不写methods&#xff0…

红队笔记--W1R3S、JARBAS、SickOS、Prime打靶练习记录

W1R3S(思路为主) 信息收集 首先使用nmap探测主机,得到192.168.190.147 接下来扫描端口,可以看到ports文件保存了三种格式 其中.nmap和屏幕输出的一样;xml这种的适合机器 nmap -sT --min-rate 10000 -p- 192.168.190.147 -oA nmapscan/ports…

深入理解 MyBatis 的缓存机制:一级缓存与二级缓存

MyBatis 是目前 Java 开发中常用的一种 ORM(对象关系映射)框架,它不仅简化了 SQL 语句的编写和管理,还提供了强大的缓存机制,用以提高数据库访问的性能。MyBatis 的缓存分为一级缓存和二级缓存,分别应用于不…

使用nvm下载多个版本node后提示vue不是内部或外部命令,执行vue create报.vuerc错误

一、使用nvm后执行含vue的相关命令提示vue不是内部或外部命令 前言:之前有项目需要切换node版本,我把node卸载了然后使用nvm下载多个版本的node。现在想通过vue create搭建vue2的项目时提示vue不是内部或外部命令,执行npm i vue/cli后仍然无…

uniapp+vue2重新进入小程序就清除缓存,设备需要重新扫码

代码 app.vue页面 <script>export default {onLaunch: function() {uni.removeStorageSync(equiId)}} </script>

学习笔记|MaxKB对接本地大模型时,选择Ollma还是vLLM?

在使用MaxKB开源知识库问答系统的过程中&#xff0c;除了对接在线大模型&#xff0c;一些用户出于资源配置、长期使用成本、安全性等多方面考虑&#xff0c;还在积极尝试通过Ollama、vLLM等模型推理框架对接本地离线大模型。而在用户实践的过程中&#xff0c;经常会对候选的模型…

电脑开启虚拟化的方法

因为最近在用模拟器玩游戏&#xff0c;所以来给大家分享一下&#xff0c;使用模拟器之前需要开启的虚拟化技术。 Windows系统开启Hyper-V功能 Windows 11&#xff1a; 按【Win】【i】打开系统设置。在【系统】一栏找到并点击【可选功能】。在界面最下方找到相关设置选项的【更…

计算机网络八股整理(一)

计算机网络八股文整理 一&#xff1a;网络模型 1&#xff1a;网络osi模型和tcp/ip模型分别介绍一下 osi模型是国际标准的网络模型&#xff0c;它由七层组成&#xff0c;从上到下分别是&#xff1a;应用层&#xff0c;表示层&#xff0c;会话层&#xff0c;传输层&#xff0c;…

Spring Boot教程之五:在 IntelliJ IDEA 中运行第一个 Spring Boot 应用程序

在 IntelliJ IDEA 中运行第一个 Spring Boot 应用程序 IntelliJ IDEA 是一个用 Java 编写的集成开发环境 (IDE)。它用于开发计算机软件。此 IDE 由 Jetbrains 开发&#xff0c;提供 Apache 2 许可社区版和商业版。它是一种智能的上下文感知 IDE&#xff0c;可用于在各种应用程序…

单片机学习笔记 9. 8×8LED点阵屏

更多单片机学习笔记&#xff1a;单片机学习笔记 1. 点亮一个LED灯单片机学习笔记 2. LED灯闪烁单片机学习笔记 3. LED灯流水灯单片机学习笔记 4. 蜂鸣器滴~滴~滴~单片机学习笔记 5. 数码管静态显示单片机学习笔记 6. 数码管动态显示单片机学习笔记 7. 独立键盘单片机学习笔记 8…