知識點回顧:
- 元組
- 可迭代對象
- os模塊
作業:對自己電腦的不同文件夾利用今天學到的知識操作下,理解下os路徑。
元組
元組的特點:
有序,可以重復,這一點和列表一樣
元組中的元素不能修改,這一點非常重要,深度學習場景中很多參數、形狀定義好了確保后續不能被修改。
很多流行的 ML/DL 庫(如 TensorFlow, PyTorch, NumPy)在其 API 中都廣泛使用了元組來表示形狀、配置等。
可以看到,元組最重要的功能是在列表之上,增加了不可修改這個需求
元組的創建
my_tuple1 = (1, 2, 3)
my_tuple2 = ('a', 'b', 'c')
my_tuple3 = (1, 'hello', 3.14, [4, 5]) # 可以包含不同類型的元素
print(my_tuple1)
print(my_tuple2)
print(my_tuple3)
# 可以省略括號
my_tuple4 = 10, 20, 'thirty' # 逗號是關鍵
print(my_tuple4)
print(type(my_tuple4)) # 看看它的類型
# 創建空元組
empty_tuple = ()
# 或者使用 tuple() 函數
empty_tuple2 = tuple()
print(empty_tuple)
print(empty_tuple2)
元組的常見用法
# 元組的索引
my_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(my_tuple[0]) # 第一個元素
print(my_tuple[2]) # 第三個元素
print(my_tuple[-1]) # 最后一個元素
# 元組的長度獲取
my_tuple = (1, 2, 3)
print(len(my_tuple))
管道工程中pipeline類接收的是一個包含多個小元組的 列表 作為輸入。
可以這樣理解這個結構:
列表 []: 定義了步驟執行的先后順序。Pipeline 會按照列表中的順序依次處理數據。之所以用列表,是未來可以對這個列表進行修改。
元組 (): 用于將每個步驟的名稱和處理對象捆綁在一起。名稱用于在后續訪問或設置參數時引用該步驟,而對象則是實際執行數據轉換或模型訓練的工具。固定了操作名+操作
不用字典因為字典是無序的。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score# 1. 加載數據
iris = load_iris()
X = iris.data
y = iris.target# 2. 劃分訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)# 3. 構建管道
# 管道按順序執行以下步驟:
# - StandardScaler(): 標準化數據(移除均值并縮放到單位方差)
# - LogisticRegression(): 邏輯回歸分類器
pipeline = Pipeline([('scaler', StandardScaler()),('logreg', LogisticRegression())
])# 4. 訓練模型
pipeline.fit(X_train, y_train)# 5. 預測
y_pred = pipeline.predict(X_test)# 6. 評估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"模型在測試集上的準確率: {accuracy:.2f}")
可迭代對象
可迭代對象 (Iterable) 是 Python 中一個非常核心的概念。簡單來說,一個可迭代對象就是指那些能夠一次返回其成員(元素)的對象,讓你可以在一個循環(比如 for 循環)中遍歷它們。
Python 中有很多內置的可迭代對象,目前我們見過的類型包括:
序列類型 (Sequence Types):
list?(列表)
tuple?(元組)
str?(字符串)
range?(范圍)
集合類型 (Set Types):
set?(集合)
字典類型 (Mapping Types):
dict?(字典) - 迭代時返回鍵 (keys)
文件對象 (File objects)
生成器 (Generators)
迭代器 (Iterators) 本身
# 列表 (list)
print("迭代列表:")
my_list = [1, 2, 3, 4, 5]
for item in my_list:print(item)# 元組 (tuple)
print("迭代元組:")
my_tuple = ('a', 'b', 'c')
for item in my_tuple:print(item)# 字符串 (str)
print("迭代字符串:")
my_string = "hello"
for char in my_string:print(char)# range (范圍)
print("迭代 range:")
for number in range(5): # 生成 0, 1, 2, 3, 4print(number)# 集合類型 (Set Types)# 集合 (set) - 注意集合是無序的,所以每次迭代的順序可能不同
print("迭代集合:")
my_set = {3, 1, 4, 1, 5, 9}
for item in my_set:print(item)# 字典 (dict) - 默認迭代時返回鍵 (keys)
print("迭代字典 (默認迭代鍵):")
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Singapore'}
for key in my_dict:print(key)# 迭代字典的值 (values)
print("迭代字典的值:")
for value in my_dict.values():print(value)