CoolFace
Datasetpublic

ysn-rfd/text-dataset-tiny-code-script-py-format

USED of tahamajs/medicine_ds_persian for .parquet file USED of Alijafarixcs2/persian-it-llama2-2k for .parquet file USED of Abirate/english_quotes for .jsonl file NEW FILES (05/12/2025) NEW FILES (12/26/2025) NEW FILES (02/15/2026)

sourceHugging Faceapache-2.0updated 4mo agoView on Hugging Face
3likes1.7kdownloads
day3_1.py116 linesDownload Raw Back to pytorch_study
1import pandas as pd
2import torch
3import numpy
4import torch.nn as nn
5import torch.optim as optim
6from sklearn.feature_extraction.text import CountVectorizer
7
8#  ۱. داده‌ها را ایجاد و ذخیره کنید
9data = {
10    "text": [
11        "This movie was great",
12        "I did not like this movie",
13        "The acting was terrible",
14        "I loved the plot",
15        "It was a boring experience",
16        "What a fantastic film!",
17        "I hated it",
18        "It was okay",
19        "Absolutely wonderful!",
20        "Not my favorite"
21        "Was very good"
22        "Very good"
23    ],
24    "label": [
25        1,  # Positive
26        0,  # Negative
27        0,  # Negative
28        1,  # Positive
29        0,  # Negative
30        1,  # Positive
31        0,  # Negative
32        0,  # Negative
33        1,  # Positive
34        0,
35        1,
36        1   # Negative
37    ]
38}
39
40# تبدیل دیکشنری به DataFrame و ذخیره در CSV
41df = pd.DataFrame(data)
42df.to_csv("data.csv", index=False)
43
44#  ۲. خواندن و پردازش داده‌ها
45df = pd.read_csv("data.csv")
46
47#  ۳. تبدیل کلمات به اعداد (Tokenization)
48vectorizer = CountVectorizer()
49X = vectorizer.fit_transform(df["text"]).toarray()
50y = df["label"].values
51
52# تبدیل داده‌ها به Tensor
53X_tensor = torch.tensor(X, dtype=torch.float32)
54y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1)
55
56#  ۴. ساخت مدل شبکه عصبی
57class SentimentAnalysisModel(nn.Module):
58    def __init__(self, input_size):
59        super(SentimentAnalysisModel, self).__init__()
60        self.fc1 = nn.Linear(input_size, 8)  # لایه‌ی مخفی با ۸ نورون
61        self.fc2 = nn.Linear(8, 1)  # خروجی (یک مقدار بین ۰ و ۱)
62        self.relu = nn.ReLU()  # تابع فعال‌ساز
63
64    def forward(self, x):
65        x = self.relu(self.fc1(x))
66        x = torch.sigmoid(self.fc2(x))  # تابع سیگموید برای خروجی بین ۰ و ۱
67        return x
68
69#  ۵. تنظیم تابع هزینه و بهینه‌ساز
70input_size = X.shape[1]  # تعداد ویژگی‌ها (کلمات منحصر به فرد)
71model = SentimentAnalysisModel(input_size)
72
73criterion = nn.BCELoss()  # تابع هزینه برای دسته‌بندی دودویی
74optimizer = optim.Adam(model.parameters(), lr=0.01)  # نرخ یادگیری ۰.۰۱
75
76#  ۶. آموزش مدل
77epochs = 100  
78
79for epoch in range(epochs):
80    # ۱. پیش‌بینی مدل
81    y_pred = model(X_tensor)
82    
83    # ۲. محاسبه‌ی هزینه (Loss)
84    loss = criterion(y_pred, y_tensor)
85    
86    # ۳. پاک کردن گرادیان‌های قبلی
87    optimizer.zero_grad()
88    
89    # ۴. محاسبه‌ی گرادیان‌ها و بروزرسانی وزن‌ها
90    loss.backward()
91    optimizer.step()
92
93    # ۵. نمایش میزان خطا هر ۱۰ مرحله
94    if (epoch+1) % 10 == 0:
95        print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")
96
97#  ۷. تست مدل
98def predict_sentiment(text):
99    # تبدیل متن ورودی به بردار ویژگی‌ها
100    text_vectorized = vectorizer.transform([text]).toarray()
101    text_tensor = torch.tensor(text_vectorized, dtype=torch.float32)
102    
103    # پیش‌بینی مدل
104    output = model(text_tensor)
105    
106    # تبدیل مقدار خروجی به برچسب ۰ یا ۱
107    prediction = 1 if output.item() > 0.5 else 0
108    
109    return "Positive" if prediction == 1 else "Negative"
110
111# 🔹 تست روی چند جمله جدید
112print(predict_sentiment("I really enjoyed this movie!"))
113print(predict_sentiment("This was the worst experience ever."))
114print(predict_sentiment("It was just okay, nothing special."))
115print(predict_sentiment("Absolutely loved the storyline!"))
116