偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Python 科學計算必備的八個庫

開發(fā)
本文我們就來聊聊 Python 科學計算必備的八個庫,并通過實際代碼示例來展示它們的應用。

在Python中,科學計算是一個非常重要的領域,它涉及到數(shù)據(jù)分析、機器學習、數(shù)值計算等多個方面。Python之所以在科學計算領域如此受歡迎,很大程度上得益于其豐富的科學計算庫。今天,我們就來聊聊Python科學計算必備的8個庫,并通過實際代碼示例來展示它們的應用。

1. NumPy

NumPy是Python中用于科學計算的基礎庫,它提供了大量的數(shù)學函數(shù)和高效的多維數(shù)組對象(ndarray)。NumPy數(shù)組是固定大小的同類型元素的集合,可以對其進行各種數(shù)學運算。

import numpy as np

# 創(chuàng)建一個一維數(shù)組
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# 輸出: [1 2 3 4 5]

# 創(chuàng)建一個二維數(shù)組
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
# 輸出:
# [[1 2 3]
#  [4 5 6]]

# 數(shù)組的基本運算
result = arr + 10
print(result)
# 輸出: [11 12 13 14 15]

2. SciPy

SciPy是建立在NumPy之上的一個庫,它提供了更多的數(shù)學算法和函數(shù),用于數(shù)值積分、優(yōu)化、線性代數(shù)、信號處理等。

from scipy.integrate import quad

# 計算定積分
def f(x):
    return x**2

integral, error = quad(f, 0, 1)
print(f"Integral: {integral}, Error: {error}")
# 輸出: Integral: 0.3333333333333333, Error: 3.700743415417188e-15

3. Pandas

Pandas是Python中用于數(shù)據(jù)分析和操作的一個強大庫,它提供了快速、靈活和表達式豐富的數(shù)據(jù)結構,旨在使“關系”或“標簽”數(shù)據(jù)的處理工作變得既簡單又直觀。

import pandas as pd

# 創(chuàng)建一個DataFrame
data = {'Name': ['Tom', 'Jerry', 'Mickey'],
        'Age': [5, 7, 8],
        'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)

print(df)
# 輸出:
#     Name  Age       City
# 0    Tom    5   New York
# 1  Jerry    7      Paris
# 2  Mickey    8     London

# 選擇數(shù)據(jù)
print(df['Age'])
# 輸出:
# 0    5
# 1    7
# 2    8
# Name: Age, dtype: int64

4. Matplotlib

Matplotlib是Python中一個非常流行的繪圖庫,它提供了一個類似于MATLAB的繪圖框架。Matplotlib可以繪制各種靜態(tài)、動態(tài)和交互式的圖表。

import matplotlib.pyplot as plt

# 繪制折線圖
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Plot')
plt.show()

5. Seaborn

Seaborn是基于Matplotlib的一個高級繪圖庫,它提供了更多的繪圖樣式和更簡潔的API,使得繪制美觀的統(tǒng)計圖形變得更容易。

import seaborn as sns
import matplotlib.pyplot as plt

# 使用Seaborn繪制散點圖
tips = sns.load_dataset("tips")
sns.scatterplot(x="total_bill", y="tip", data=tips)
plt.show()

6. Scikit-learn

Scikit-learn是Python中用于機器學習的庫,它提供了大量的算法和工具,用于數(shù)據(jù)挖掘和數(shù)據(jù)分析。

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# 加載Iris數(shù)據(jù)集
iris = load_iris()
X = iris.data
y = iris.target

# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 創(chuàng)建KNN分類器
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)

# 預測并計算準確率
y_pred = knn.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
# 輸出: Accuracy: 0.9666666666666667

7. SymPy

SymPy是Python中用于符號數(shù)學的庫,它可以處理各種數(shù)學表達式,進行符號計算、代數(shù)運算、微積分等。

import sympy as sp

# 定義符號變量
x = sp.symbols('x')

# 進行符號計算
expr = x**2 + 2*x + 1
print(f"Expression: {expr}")
# 輸出: Expression: x**2 + 2*x + 1

# 因式分解
factored_expr = sp.factor(expr)
print(f"Factored Expression: {factored_expr}")
# 輸出: Factored Expression: (x + 1)**2

8. NetworkX

NetworkX是Python中用于創(chuàng)建、操作和研究復雜網絡的結構、動態(tài)和功能的庫。它可以用于社交網絡分析、生物信息學、語言學等多個領域。

import networkx as nx
import matplotlib.pyplot as plt

# 創(chuàng)建一個無向圖
G = nx.Graph()

# 添加節(jié)點和邊
G.add_node(1)
G.add_nodes_from([2, 3, 4, 5])
G.add_edge(1, 2)
G.add_edges_from([(2, 3), (3, 4), (4, 5), (5, 1)])

# 繪制圖形
nx.draw(G, with_labels=True)
plt.show()

實戰(zhàn)案例:使用Scikit-learn進行鳶尾花數(shù)據(jù)集分類

在這個實戰(zhàn)案例中,我們將使用Scikit-learn庫對鳶尾花數(shù)據(jù)集進行分類。鳶尾花數(shù)據(jù)集是一個經典的數(shù)據(jù)集,包含了150個樣本,每個樣本有4個特征(花萼長度、花萼寬度、花瓣長度、花瓣寬度),目標是將這些樣本分為3個類別(Setosa、Versicolor、Virginica)。

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix

# 加載數(shù)據(jù)集
iris = load_iris()
X = iris.data
y = iris.target

# 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 創(chuàng)建隨機森林分類器
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)

# 預測
y_pred = clf.predict(X_test)

# 輸出分類報告和混淆矩陣
print("Classification Report:")
print(classification_report(y_test, y_pred))
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))

在這個案例中,我們首先加載了鳶尾花數(shù)據(jù)集,并將其劃分為訓練集和測試集。然后,我們使用隨機森林分類器對訓練集進行訓練,并對測試集進行預測。最后,我們輸出了分類報告和混淆矩陣來評估模型的性能。

總結

本文介紹了Python科學計算中必備的8個庫:NumPy、SciPy、Pandas、Matplotlib、Seaborn、Scikit-learn、SymPy和NetworkX。每個庫都有其獨特的功能和應用場景,從基礎的數(shù)據(jù)處理到高級的機器學習算法,這些庫為Python在科學計算領域提供了強大的支持。

責任編輯:趙寧寧 來源: 小白PythonAI編程
相關推薦

2022-08-26 14:41:47

Python數(shù)據(jù)科學開源

2025-05-09 09:26:12

2022-08-16 10:32:08

Python數(shù)據(jù)科學

2021-06-29 10:03:45

數(shù)據(jù)科學機器學習算法

2024-01-26 06:25:09

PyCharm插件代碼

2018-07-23 14:53:44

Python數(shù)據(jù)科學函數(shù)

2022-12-07 12:33:22

云計算

2025-03-20 00:00:05

2025-04-27 08:35:00

Python數(shù)據(jù)分析編程

2013-06-07 10:52:18

移動應用移動產品設計

2022-05-11 07:50:15

React UI組件庫前端

2011-11-08 11:43:36

CIO云計算

2022-02-10 15:22:05

Python開發(fā)數(shù)據(jù)科學

2024-01-09 18:03:30

開發(fā)者插件代碼

2015-06-05 16:37:55

2021-08-02 09:29:08

Vscode開發(fā)Web

2018-06-12 10:37:12

云計算遷移步驟

2025-02-26 11:05:03

2022-08-03 14:51:18

pandasPython

2022-05-15 08:07:12

云計算云服務
點贊
收藏

51CTO技術棧公眾號