Python神器盤點!20個數(shù)據(jù)科學(xué)庫打造數(shù)據(jù)魔法世界!
數(shù)據(jù)科學(xué)家和分析師常常使用 Python 來處理數(shù)據(jù)、進(jìn)行分析和可視化。Python生態(tài)系統(tǒng)中有許多庫,但有一些庫是數(shù)據(jù)科學(xué)家日常工作中必不可少的。本文將深入介紹 20 個重要的 Python 庫,包括示例代碼和用例。
1. NumPy
NumPy 是 Python 中用于科學(xué)計算的基礎(chǔ)庫,主要用于數(shù)組處理。它提供了高性能的多維數(shù)組對象和用于處理這些數(shù)組的工具。
import numpy as np
# 創(chuàng)建一個數(shù)組
array = np.array([1, 2, 3, 4, 5])
# 數(shù)組運(yùn)算
result = array * 2
print(result)
2. Pandas
Pandas 是用于數(shù)據(jù)操作和分析的強(qiáng)大工具,提供了用于處理表格數(shù)據(jù)的數(shù)據(jù)結(jié)構(gòu)。
import pandas as pd
# 創(chuàng)建一個 DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# 顯示數(shù)據(jù)框架
print(df)
3. Matplotlib
Matplotlib 是一個用于創(chuàng)建二維圖表的庫,支持多種圖表類型。
import matplotlib.pyplot as plt
# 繪制折線圖
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
4. Seaborn
Seaborn 是建立在 Matplotlib 之上的統(tǒng)計數(shù)據(jù)可視化庫,提供更多高級繪圖選項。
import seaborn as sns
# 繪制熱圖
data = np.random.rand(10, 12)
sns.heatmap(data)
plt.show()
5. Scikit-learn
Scikit-learn 是用于機(jī)器學(xué)習(xí)的庫,提供了許多常用的機(jī)器學(xué)習(xí)算法和工具。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# 加載鳶尾花數(shù)據(jù)集
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
# 訓(xùn)練支持向量機(jī)模型
model = SVC()
model.fit(X_train, y_train)
6. TensorFlow
TensorFlow 是一個用于機(jī)器學(xué)習(xí)的強(qiáng)大框架,特別擅長深度學(xué)習(xí)。
import tensorflow as tf
# 創(chuàng)建神經(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')
])
7. Keras
Keras 是建立在 TensorFlow、Theano 和 CNTK 之上的深度學(xué)習(xí)庫,提供了高級神經(jīng)網(wǎng)絡(luò)的構(gòu)建和訓(xùn)練。
from keras.models import Sequential
from keras.layers import Dense
# 創(chuàng)建神經(jīng)網(wǎng)絡(luò)模型
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
8. Statsmodels
Statsmodels 是一個用于擬合統(tǒng)計模型并進(jìn)行統(tǒng)計測試和數(shù)據(jù)探索的庫。
import statsmodels.api as sm
# 擬合線性回歸模型
X = np.random.rand(100, 2)
y = X.dot(np.array([1, 2])) + np.random.normal(0, 0.1, 100)
model = sm.OLS(y, X).fit()
print(model.summary())
9. SciPy
SciPy 是建立在 NumPy 之上的庫,提供了許多數(shù)學(xué)、科學(xué)和工程常用的算法。
from scipy.optimize import minimize
# 定義優(yōu)化函數(shù)
def rosen(x):
return sum(100.0 * (x[1:] - x[:-1]**2)**2 + (1 - x[:-1])**2)
# 最小化函數(shù)
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
res = minimize(rosen, x0, method='nelder-mead', options={'xatol': 1e-8, 'disp': True})
print(res.x)
10. Plotly
Plotly 是一個交互式可視化庫,支持創(chuàng)建絢麗的圖表和可視化。
import plotly.express as px
# 繪制散點圖
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
11. NetworkX
NetworkX 是用于創(chuàng)建、操作和研究復(fù)雜網(wǎng)絡(luò)的庫。
import networkx as nx
# 創(chuàng)建一個圖
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2, 3])
G.add_edge(1, 2)
12. NLTK
NLTK(Natural Language Toolkit)是一個用于自然語言處理的庫,提供了處理文本和語言數(shù)據(jù)的工具。
import nltk
from nltk.tokenize import word_tokenize
text = "Hello, how are you?"
tokens = word_tokenize(text)
print(tokens)
13. Beautiful Soup
Beautiful Soup 是一個用于解析 HTML 和 XML 文件的庫,方便從網(wǎng)頁中提取信息。
from bs4 import BeautifulSoup
import requests
# 從網(wǎng)頁抓取信息
url = "https://en.wikipedia.org/wiki/Data_science"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title)
14. Gensim
Gensim 是一個用于文本建模和文檔相似性分析的庫,特別擅長處理大型文本語料庫。
from gensim.summarization import keywords
from gensim import corpora
# 提取關(guān)鍵字
text = "Natural language processing (NLP) is a field " \
"focused on making sense of and working with text data."
kw = keywords(text)
print(kw)
15. PyTorch
PyTorch 是另一個用于深度學(xué)習(xí)的庫,提供了張量計算和動態(tài)神經(jīng)網(wǎng)絡(luò)。
import torch
# 創(chuàng)建張量
x = torch.rand(5, 3)
print(x)
16. Dask
Dask 是用于并行計算的庫,能夠處理比內(nèi)存更大的數(shù)據(jù)集。
import dask.dataframe as dd
# 創(chuàng)建大型數(shù)據(jù)框架
df = dd.read_csv('large_dataset.csv')
result = df.groupby('column').value.mean().compute()
print(result)
17. Bokeh
Bokeh 是一個交互式可視化庫,適用于創(chuàng)建漂亮的數(shù)據(jù)可視化。
from bokeh.plotting import figure, output_file, show
# 繪制直方圖
output_file("histogram.html")
p = figure()
p.vbar(x=[1, 2, 3], width=0.5, bottom=0, top=[1, 2, 3])
show(p)
18. TensorFlow Probability
TensorFlow Probability 是建立在 TensorFlow 之上的用于概率推斷和統(tǒng)計建模的庫。
import tensorflow_probability as tfp
# 定義正態(tài)分布
normal = tfp.distributions.Normal(loc=0., scale=1.)
samples = normal.sample(100)
print(samples)
19. Yellowbrick
Yellowbrick 是一個用于機(jī)器學(xué)習(xí)模型選擇和可視化的庫。
from yellowbrick.datasets import load_concrete
from yellowbrick.regressor import ResidualsPlot
from sklearn.linear_model import Ridge
# 加載數(shù)據(jù)集
X, y = load_concrete()
# 可視化回歸殘差
model = Ridge()
visualizer = ResidualsPlot(model)
visualizer.fit(X, y)
visualizer.show()
20. XGBoost
XGBoost 是一個用于梯度提升的庫,提供了高效的梯度提升樹實現(xiàn)。
import xgboost as xgb
# 加載數(shù)據(jù)
data = np.random.rand(5, 10)
labels = np.random.randint(2, size=5)
# 構(gòu)建 DMatrix
dtrain = xgb.DMatrix(data, label=labels)
這些 Python 庫是數(shù)據(jù)科學(xué)家在日常工作中經(jīng)常使用的關(guān)鍵工具。通過使用它們,可以更加高效地處理數(shù)據(jù)、進(jìn)行分析和可視化,從而加速數(shù)據(jù)科學(xué)項目的開發(fā)和部署。