成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

12 種 Python 在科學計算中的核心庫

開發(fā)
今天我們介紹了 12 種 Python 在科學計算中的核心庫,每種庫都有其獨特的功能和應用場景,通過實際的代碼示例,我們展示了如何使用這些庫來處理和分析數(shù)據(jù)。

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)域更加得心應手。

責任編輯:趙寧寧 來源: 小白PythonAI編程
相關(guān)推薦

2024-11-12 10:57:14

NumPyPython

2024-12-20 09:00:00

Python科學計算

2024-10-11 10:00:00

Python編程

2024-12-30 07:47:15

Python科學計算

2019-04-24 11:41:32

云計算開發(fā)數(shù)據(jù)中心

2020-03-19 22:16:05

數(shù)據(jù)概率分布Python實現(xiàn)

2019-11-11 16:44:20

機器學習Python算法

2023-11-24 08:47:36

ScipyPython

2019-11-26 09:05:32

Python機器學習深度學習

2019-08-19 14:47:28

數(shù)據(jù)庫軟件技術(shù)

2022-07-11 06:00:00

云計算成本技巧

2012-08-06 09:34:49

云計算編程語言

2021-02-04 17:09:17

Python 開發(fā)編程語言

2018-04-20 11:21:07

云計算負載均衡HTTP

2011-07-01 11:30:19

云計算數(shù)據(jù)吞吐量集裝箱

2023-10-08 07:40:29

2021-07-29 09:00:00

Python工具機器學習

2019-11-05 10:07:26

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

2019-07-22 15:37:56

CPU核心GPU

2018-06-27 10:45:12

數(shù)據(jù)Python程序
點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 日本欧美大片 | 精品视频一区二区 | 免费看a | 中国免费黄色片 | 日韩欧美在线观看 | 国产一二区视频 | 中文字幕日本一区二区 | 久久久久久美女 | 久久精品女人天堂av | 国产精品久久国产精品久久 | 欧美成人激情 | 久久99国产精一区二区三区 | 国产91在线播放 | 日韩视频在线播放 | 四虎影院在线播放 | yeyeav| 国产女人第一次做爰毛片 | 国产久视频 | 国产精品精品视频一区二区三区 | 日韩精品一区二区三区高清免费 | 色桃网 | 亚洲福利一区 | 精品香蕉一区二区三区 | 四虎影院免费在线 | 日韩在线观看一区 | 91一区二区 | 久久久国产一区二区 | 在线免费观看黄网 | 操人网 | 国产人成在线观看 | 日韩在线看片 | 中文字幕亚洲精品在线观看 | 欧美性猛交一区二区三区精品 | 在线欧美视频 | 成人永久免费 | 亚洲播放 | 国产成人福利在线观看 | 天堂一区 | 日本精品视频在线 | 国产精品成人国产乱 | av一级毛片 |