TensorFlow 分析 iris 數(shù)據(jù)的源碼
當(dāng)使用TensorFlow來分析Iris數(shù)據(jù)集時,可以使用經(jīng)典的機器學(xué)習(xí)問題——鳶尾花分類任務(wù)。以下是一個使用TensorFlow庫來訓(xùn)練和評估模型的基本源代碼示例:
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
# 加載Iris數(shù)據(jù)集
iris = load_iris()
X = iris.data
y = iris.target
# 對標(biāo)簽進(jìn)行獨熱編碼
enc = OneHotEncoder()
y = enc.fit_transform(y[:, None]).toarray()
# 將數(shù)據(jù)集拆分為訓(xùn)練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 構(gòu)建模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(4,)),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
# 編譯模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 訓(xùn)練模型
model.fit(X_train, y_train, epochs=50, batch_size=16, verbose=1)
# 評估模型
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f'Test loss: {loss:.4f}')
print(f'Test accuracy: {accuracy:.4f}')
上述代碼中,我們首先導(dǎo)入了所需的庫和模塊。然后,加載Iris數(shù)據(jù)集并將特征數(shù)據(jù) X
和標(biāo)簽數(shù)據(jù) y
分別存儲。接下來,我們使用 OneHotEncoder
對標(biāo)簽進(jìn)行獨熱編碼,以便在多類分類問題中使用。
然后,我們將數(shù)據(jù)集分為訓(xùn)練集和測試集,使用 train_test_split
函數(shù),其中測試集占比為20%。
接下來,我們構(gòu)建了一個簡單的神經(jīng)網(wǎng)絡(luò)模型,使用 tf.keras.Sequential
創(chuàng)建一個順序模型。該模型由三個密集連接層組成,使用ReLU激活函數(shù),并在最后一層使用softmax激活函數(shù)來輸出概率分布。
然后,我們編譯模型,指定優(yōu)化器、損失函數(shù)和評估指標(biāo)。這里使用Adam優(yōu)化器和交叉熵?fù)p失函數(shù)。
接下來,我們使用訓(xùn)練集數(shù)據(jù)進(jìn)行模型訓(xùn)練,使用 fit
方法,并指定訓(xùn)練的迭代次數(shù)、批次大小和詳細(xì)模式。
最后,我們使用測試集數(shù)據(jù)評估模型的性能,使用 evaluate
方法,并打印出損失值和準(zhǔn)確率。
當(dāng)使用PyTorch來分析Iris數(shù)據(jù)集時,可以使用與之前相似的機器學(xué)習(xí)問題——鳶尾花分類任務(wù)。以下是一個使用PyTorch庫來訓(xùn)練和評估模型的基本源代碼示例:
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from torch.utils.data import Dataset, DataLoader
# 自定義數(shù)據(jù)集類
class IrisDataset(Dataset):
def __init__(self, data, targets):
self.data = data
self.targets = targets
def __len__(self):
return len(self.targets)
def __getitem__(self, idx):
return self.data[idx], self.targets[idx]
# 加載Iris數(shù)據(jù)集
iris = load_iris()
X = iris.data
y = iris.target
# 對標(biāo)簽進(jìn)行獨熱編碼
enc = OneHotEncoder()
y = enc.fit_transform(y[:, None]).toarray()
# 將數(shù)據(jù)集拆分為訓(xùn)練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 將數(shù)據(jù)轉(zhuǎn)換為PyTorch張量
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32)
X_test = torch.tensor(X_test, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.float32)
# 創(chuàng)建數(shù)據(jù)加載器
train_dataset = IrisDataset(X_train, y_train)
train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
# 構(gòu)建模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(4, 10)
self.fc2 = nn.Linear(10, 10)
self.fc3 = nn.Linear(10, 3)
self.relu = nn.ReLU()
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.softmax(self.fc3(x))
return x
model = Net()
# 定義損失函數(shù)和優(yōu)化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# 訓(xùn)練模型
num_epochs = 50
for epoch in range(num_epochs):
for inputs, targets in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, torch.argmax(targets, dim=1))
loss.backward()
optimizer.step()
# 評估模型
with torch.no_grad():
outputs = model(X_test)
predicted = torch.argmax(outputs, dim=1)
accuracy = (predicted == torch.argmax(y_test, dim=1)).sum().item() / len(y_test)
print(f'Test accuracy: {accuracy:.4f}')
在上述代碼中,我們首先導(dǎo)入了所需的庫和模塊。然后,加載Iris數(shù)據(jù)集并將特征數(shù)據(jù) X
和標(biāo)簽數(shù)據(jù) y
分別存儲。接下來,我們使用 OneHotEncoder
對標(biāo)簽進(jìn)行獨熱編碼,以便在多類分類問題中使用。
然后,我們將數(shù)據(jù)集分為訓(xùn)練集和測試集,使用 train_test_split
函數(shù),其中測試集占比為20%。
接著,我們定義了一個自定義的數(shù)據(jù)集類 IrisDataset
,用于加載數(shù)據(jù)集并定義數(shù)據(jù)的獲取方式。
然后,我們將數(shù)據(jù)轉(zhuǎn)換為PyTorch張量,并創(chuàng)建了訓(xùn)練數(shù)據(jù)集的數(shù)據(jù)加載器,使用 DataLoader
。
接下來,我們構(gòu)建了一個簡單的神經(jīng)網(wǎng)絡(luò)模型,使用 nn.Module
創(chuàng)建一個自定義的網(wǎng)絡(luò)類 Net
。該模型由三個全連接層組成,使用ReLU激活函數(shù)和Softmax函數(shù),并定義了前向傳播方法。
然后,我們定義了損失函數(shù) nn.CrossEntropyLoss
和優(yōu)化器 optim.Adam
。
接下來,我們使用訓(xùn)練數(shù)據(jù)集進(jìn)行模型訓(xùn)練。我們迭代數(shù)據(jù)加載器中的每個批次,并執(zhí)行前向傳播、計算損失、反向傳播和參數(shù)更新的步驟。
最后,我們使用測試集數(shù)據(jù)評估模型的性能。我們計算模型在測試集上的準(zhǔn)確率,并打印出結(jié)果。文章來源:http://www.zghlxwxcb.cn/news/detail-567232.html
看的出,TensorFlow實現(xiàn)起來更簡介明了些。而Pytorch實現(xiàn)起來,涉及到很多深度學(xué)習(xí)的底層概念。方便我們更深一步的理解理論和具體操作流程。文章來源地址http://www.zghlxwxcb.cn/news/detail-567232.html
到了這里,關(guān)于TensorFlow和Pytorch分析經(jīng)典數(shù)據(jù)iris實現(xiàn)區(qū)別和對比的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!