在前几篇文章中,我们探讨了 Python 的基础语法、面向对象编程、函数式编程、元编程、性能优化和调试技巧。本文将深入探讨 Python 在数据科学和机器学习中的应用,并通过实战项目帮助你掌握这些技术。
1. 数据科学基础
数据科学是使用科学方法、算法和系统从数据中提取知识和见解的跨学科领域。Python 是数据科学的首选语言,提供了丰富的库和工具。
1.1 使用 pandas
进行数据处理
pandas
是一个强大的数据处理库,提供了高效的数据结构和数据分析工具。
import pandas as pd
# 创建 DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# 查看 DataFrame
print(df)
# 选择列
print(df['Name'])
# 过滤行
print(df[df['Age'] > 30])
1.2 使用 matplotlib
进行数据可视化
matplotlib
是一个广泛使用的数据可视化库,可以创建各种静态、动态和交互式图表。
import matplotlib.pyplot as plt
# 数据
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# 绘制折线图
plt.plot(x, y)
# 添加标题和标签
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# 显示图表
plt.show()
1.3 使用 scikit-learn
进行机器学习
scikit-learn
是一个广泛使用的机器学习库,提供了各种算法和工具。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.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)
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
2. 机器学习实战项目
2.1 使用 pandas
和 matplotlib
进行数据分析
我们将使用 pandas
和 matplotlib
对 Titanic 数据集进行数据分析。
import pandas as pd
import matplotlib.pyplot as plt
# 加载数据集
url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
df = pd.read_csv(url)
# 查看数据集
print(df.head())
# 统计生存率
survival_rate = df['Survived'].mean()
print(f"Survival Rate: {survival_rate}")
# 按性别统计生存率
gender_survival = df.groupby('Sex')['Survived'].mean()
print(gender_survival)
# 绘制生存率柱状图
gender_survival.plot(kind='bar')
plt.title("Survival Rate by Gender")
plt.xlabel("Gender")
plt.ylabel("Survival Rate")
plt.show()
2.2 使用 scikit-learn
进行房价预测
我们将使用 scikit-learn
对 Boston Housing 数据集进行房价预测。
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 加载数据集
boston = load_boston()
X, y = boston.data, boston.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)
# 评估模型
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
3. 总结
本文深入探讨了 Python 在数据科学和机器学习中的应用,并通过实战项目帮助你掌握这些技术。通过本文的学习,你应该能够使用 Python 进行数据处理、数据可视化和机器学习。
4. 进一步学习资源
希望本文能够帮助你进一步提升 Python 编程技能,祝你在编程的世界中不断进步!