12 種 Python 在科學(xué)計(jì)算中的核心庫(kù)
Python 是一門(mén)非常強(qiáng)大的編程語(yǔ)言,尤其在科學(xué)計(jì)算領(lǐng)域有著廣泛的應(yīng)用。今天我們就來(lái)聊聊 12 種 Python 在科學(xué)計(jì)算中的核心庫(kù),幫助你更好地理解和使用它們。
1.NumPy
NumPy 是 Python 中用于處理數(shù)值數(shù)據(jù)的基礎(chǔ)庫(kù)。它提供了高效的數(shù)組對(duì)象和大量的數(shù)學(xué)函數(shù)。
import numpy as np
# 創(chuàng)建一個(gè)一維數(shù)組
arr = np.array([1, 2, 3, 4, 5])
print(arr) # 輸出: [1 2 3 4 5]
# 創(chuàng)建一個(gè)多維數(shù)組
multi_dim_arr = np.array([[1, 2, 3], [4, 5, 6]])
print(multi_dim_arr)
# 輸出:
# [[1 2 3]
# [4 5 6]]
# 數(shù)組操作
sum_arr = np.sum(arr)
mean_arr = np.mean(arr)
print(sum_arr, mean_arr) # 輸出: 15 3.0
2.Pandas
Pandas 是一個(gè)強(qiáng)大的數(shù)據(jù)處理和分析庫(kù),特別適合處理表格數(shù)據(jù)。
import pandas as pd
# 創(chuàng)建一個(gè) DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
# 輸出:
# Name Age
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
# 數(shù)據(jù)篩選
filtered_df = df[df['Age'] > 30]
print(filtered_df)
# 輸出:
# Name Age
# 2 Charlie 35
3.Matplotlib
Matplotlib 是一個(gè)常用的繪圖庫(kù),可以生成各種靜態(tài)、動(dòng)態(tài)和交互式的圖表。
import matplotlib.pyplot as plt
# 繪制簡(jiǎn)單的折線圖
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
4.SciPy
SciPy 是一個(gè)基于 NumPy 的科學(xué)計(jì)算庫(kù),提供了許多高級(jí)的數(shù)學(xué)、科學(xué)和工程計(jì)算功能。
from scipy import stats
# 計(jì)算兩個(gè)樣本的 t 檢驗(yàn)
sample1 = [1, 2, 3, 4, 5]
sample2 = [2, 3, 4, 5, 6]
t_stat, p_value = stats.ttest_ind(sample1, sample2)
print(t_stat, p_value) # 輸出: -2.23606797749979 0.06935067780645372
5.Scikit-learn
Scikit-learn 是一個(gè)機(jī)器學(xué)習(xí)庫(kù),提供了大量的監(jiān)督和無(wú)監(jiān)督學(xué)習(xí)算法。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
# 加載數(shù)據(jù)集
iris = load_iris()
X, y = iris.data, iris.target
# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 訓(xùn)練模型
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# 預(yù)測(cè)
predictions = knn.predict(X_test)
print(predictions)
# 輸出: [2 1 0 2 0 2 0 1 1 1 2 1 1 1 2 0 1 1 0 0 2 1 0 0 2 0 2 2 2 0]
6.TensorFlow
TensorFlow 是一個(gè)由 Google 開(kāi)發(fā)的深度學(xué)習(xí)框架,支持多種平臺(tái)和設(shè)備。
import tensorflow as tf
# 創(chuàng)建一個(gè)簡(jiǎn)單的神經(jīng)網(wǎng)絡(luò)
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(4,)),
tf.keras.layers.Dense(3, activation='softmax')
])
# 編譯模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 訓(xùn)練模型
model.fit(X_train, y_train, epochs=10, batch_size=10)
7.PyTorch
PyTorch 是另一個(gè)流行的深度學(xué)習(xí)框架,以其動(dòng)態(tài)計(jì)算圖和易用性著稱。
import torch
import torch.nn as nn
import torch.optim as optim
# 定義一個(gè)簡(jiǎn)單的神經(jīng)網(wǎng)絡(luò)
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(4, 10)
self.fc2 = nn.Linear(10, 3)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 實(shí)例化模型
model = SimpleNet()
# 定義損失函數(shù)和優(yōu)化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
# 訓(xùn)練模型
for epoch in range(100):
optimizer.zero_grad()
outputs = model(torch.tensor(X_train, dtype=torch.float32))
loss = criterion(outputs, torch.tensor(y_train, dtype=torch.long))
loss.backward()
optimizer.step()
8.Seaborn
Seaborn 是一個(gè)基于 Matplotlib 的高級(jí)繪圖庫(kù),提供了更多統(tǒng)計(jì)圖形的支持。
import seaborn as sns
# 繪制箱形圖
sns.boxplot(x='Name', y='Age', data=df)
plt.show()
9. SymPy
SymPy 是一個(gè)符號(hào)計(jì)算庫(kù),可以用于代數(shù)、微積分等數(shù)學(xué)問(wèn)題的符號(hào)求解。
from sympy import symbols, diff
# 定義符號(hào)變量
x = symbols('x')
# 定義函數(shù)
f = x**2 + 2*x + 1
# 求導(dǎo)
f_prime = diff(f, x)
print(f_prime) # 輸出: 2*x + 2
10. NetworkX
NetworkX 是一個(gè)用于創(chuàng)建、操作和研究復(fù)雜網(wǎng)絡(luò)結(jié)構(gòu)的庫(kù)。
import networkx as nx
# 創(chuàng)建一個(gè)簡(jiǎn)單的圖
G = nx.Graph()
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('C', 'A')
# 繪制圖
nx.draw(G, with_labels=True)
plt.show()
11. Statsmodels
Statsmodels 是一個(gè)用于統(tǒng)計(jì)建模和測(cè)試的庫(kù),提供了大量的統(tǒng)計(jì)模型和方法。
import statsmodels.api as sm
# 加載數(shù)據(jù)
data = sm.datasets.fair.load_pandas().data
# 添加常數(shù)項(xiàng)
data['const'] = 1
# 定義因變量和自變量
y = data['affairs']
X = data[['const', 'rate_marriage', 'age', 'yrs_married', 'children', 'religious', 'educ', 'occupation', 'occupation_husb']]
# 擬合線性回歸模型
model = sm.OLS(y, X).fit()
print(model.summary())
12. Plotly
Plotly 是一個(gè)交互式繪圖庫(kù),支持多種圖表類型和交互功能。
import plotly.express as px
# 繪制散點(diǎn)圖
fig = px.scatter(x=[1, 2, 3, 4, 5], y=[2, 3, 5, 7, 11])
fig.show()
實(shí)戰(zhàn)案例:股票數(shù)據(jù)分析
假設(shè)我們要分析某只股票的歷史價(jià)格數(shù)據(jù),并繪制其收盤(pán)價(jià)的折線圖。
import pandas as pd
import matplotlib.pyplot as plt
# 讀取股票數(shù)據(jù)
df = pd.read_csv('stock_data.csv')
# 轉(zhuǎn)換日期格式
df['Date'] = pd.to_datetime(df['Date'])
# 設(shè)置日期為索引
df.set_index('Date', inplace=True)
# 繪制收盤(pán)價(jià)折線圖
plt.figure(figsize=(10, 5))
plt.plot(df['Close'])
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.title('Stock Closing Price Over Time')
plt.show()
在這個(gè)案例中,我們使用了 Pandas 來(lái)讀取和處理 CSV 文件中的股票數(shù)據(jù),并使用 Matplotlib 繪制了收盤(pán)價(jià)的折線圖。通過(guò)這個(gè)案例,你可以看到這些庫(kù)在實(shí)際應(yīng)用中的強(qiáng)大功能。
總結(jié)
今天我們介紹了 12 種 Python 在科學(xué)計(jì)算中的核心庫(kù),包括 NumPy、Pandas、Matplotlib、SciPy、Scikit-learn、TensorFlow、PyTorch、Seaborn、SymPy、NetworkX、Statsmodels 和 Plotly。每種庫(kù)都有其獨(dú)特的功能和應(yīng)用場(chǎng)景,通過(guò)實(shí)際的代碼示例,我們展示了如何使用這些庫(kù)來(lái)處理和分析數(shù)據(jù)。希望這些內(nèi)容能幫助你在科學(xué)計(jì)算領(lǐng)域更加得心應(yīng)手。