|
Pwtorch yordamida misol (oddiy neyron tarmoq uchun)
|
bet | 14/182 | Sana | 19.05.2024 | Hajmi | 5,69 Mb. | | #244351 |
Bog'liq Python sun\'iy intellekt texnologiyasi Dasrlik 20243. Pwtorch yordamida misol (oddiy neyron tarmoq uchun)
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Ma’lumotlarni yuklash (Iris ma’lumotlar to‘plamiga misol)
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
# Ma’lumotlarni o‘qitish va test namunalariga bo‘lish
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Ma’lumotlarni pwtorch tensorlariga aylantirish
X_train_tensor = torch.Tensor(X_train)
y_train_tensor = torch.Tensor(y_train).long()
# Oddiy neyron tarmoqni aniqlash
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(4, 64)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(64, 3)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# Model, yo‘qotish funktsiyasi va optimizatorni ishga tushirish
model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Modelni o‘qitish
for epoch in range(50):
outputs = model(X_train_tensor)
loss = criterion(outputs, y_train_tensor)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Modelning aniqligini baholash
with torch.no_grad():
X_test_tensor = torch.Tensor(X_test)
predictions = model(X_test_tensor)
_, predicted_labels = torch.max(predictions, 1)
accuracy = accuracy_score(y_test, predicted_labels.numpy())
print(f"Test Accuracy: {accuracy}")
Bu Python-da mashinali o‘qitish kutubxonalaridan foydalanishning oddiy misollari. Haqiqiy loyihalarda siz o‘zingizning vazifangiz talablariga qarab model parametrlarini sozlashingiz, o‘zaro tekshirishni amalga oshirishingiz va h.k.
Python-da tabiiy tilni qayta ishlash (NLP) kutubxonalaridan foydalanish misollarini ko‘rib chiqaylik:
NLTK (Natural Language Toolkit):
Nltk kutubxonasini o‘rnatish:
pip install nltk
|
| |