12 種 Python 在科學計算中的核心庫
Python 是一門非常強大的編程語言,尤其在科學計算領(lǐng)域有著廣泛的應用。今天我們就來聊聊 12 種 Python 在科學計算中的核心庫,幫助你更好地理解和使用它們。
1.NumPy
NumPy 是 Python 中用于處理數(shù)值數(shù)據(jù)的基礎庫。它提供了高效的數(shù)組對象和大量的數(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ù)組
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 是一個強大的數(shù)據(jù)處理和分析庫,特別適合處理表格數(shù)據(jù)。
import pandas as pd
# 創(chuàng)建一個 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 是一個常用的繪圖庫,可以生成各種靜態(tài)、動態(tài)和交互式的圖表。
import matplotlib.pyplot as plt
# 繪制簡單的折線圖
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 是一個基于 NumPy 的科學計算庫,提供了許多高級的數(shù)學、科學和工程計算功能。
from scipy import stats
# 計算兩個樣本的 t 檢驗
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 是一個機器學習庫,提供了大量的監(jiān)督和無監(jiān)督學習算法。
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_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 訓練模型
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# 預測
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 是一個由 Google 開發(fā)的深度學習框架,支持多種平臺和設備。
import tensorflow as tf
# 創(chuàng)建一個簡單的神經(jīng)網(wǎng)絡
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'])
# 訓練模型
model.fit(X_train, y_train, epochs=10, batch_size=10)
7.PyTorch
PyTorch 是另一個流行的深度學習框架,以其動態(tài)計算圖和易用性著稱。
import torch
import torch.nn as nn
import torch.optim as optim
# 定義一個簡單的神經(jīng)網(wǎng)絡
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
# 實例化模型
model = SimpleNet()
# 定義損失函數(shù)和優(yōu)化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
# 訓練模型
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 是一個基于 Matplotlib 的高級繪圖庫,提供了更多統(tǒng)計圖形的支持。
import seaborn as sns
# 繪制箱形圖
sns.boxplot(x='Name', y='Age', data=df)
plt.show()
9. SymPy
SymPy 是一個符號計算庫,可以用于代數(shù)、微積分等數(shù)學問題的符號求解。
from sympy import symbols, diff
# 定義符號變量
x = symbols('x')
# 定義函數(shù)
f = x**2 + 2*x + 1
# 求導
f_prime = diff(f, x)
print(f_prime) # 輸出: 2*x + 2
10. NetworkX
NetworkX 是一個用于創(chuàng)建、操作和研究復雜網(wǎng)絡結(jié)構(gòu)的庫。
import networkx as nx
# 創(chuàng)建一個簡單的圖
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 是一個用于統(tǒng)計建模和測試的庫,提供了大量的統(tǒng)計模型和方法。
import statsmodels.api as sm
# 加載數(shù)據(jù)
data = sm.datasets.fair.load_pandas().data
# 添加常數(shù)項
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 是一個交互式繪圖庫,支持多種圖表類型和交互功能。
import plotly.express as px
# 繪制散點圖
fig = px.scatter(x=[1, 2, 3, 4, 5], y=[2, 3, 5, 7, 11])
fig.show()
實戰(zhàn)案例:股票數(shù)據(jù)分析
假設我們要分析某只股票的歷史價格數(shù)據(jù),并繪制其收盤價的折線圖。
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'])
# 設置日期為索引
df.set_index('Date', inplace=True)
# 繪制收盤價折線圖
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()
在這個案例中,我們使用了 Pandas 來讀取和處理 CSV 文件中的股票數(shù)據(jù),并使用 Matplotlib 繪制了收盤價的折線圖。通過這個案例,你可以看到這些庫在實際應用中的強大功能。
總結(jié)
今天我們介紹了 12 種 Python 在科學計算中的核心庫,包括 NumPy、Pandas、Matplotlib、SciPy、Scikit-learn、TensorFlow、PyTorch、Seaborn、SymPy、NetworkX、Statsmodels 和 Plotly。每種庫都有其獨特的功能和應用場景,通過實際的代碼示例,我們展示了如何使用這些庫來處理和分析數(shù)據(jù)。希望這些內(nèi)容能幫助你在科學計算領(lǐng)域更加得心應手。