🧠 مبانی TensorFlow
TensorFlow یک کتابخانه متنباز برای یادگیری ماشین و یادگیری عمیق است که توسط گوگل توسعه داده شده است. TensorFlow با ارائه API سطح بالا (Keras) و API سطح پایین، انعطافپذیری بالایی برای ساخت و آموزش مدلهای مختلف فراهم میکند [citation:5][citation:8].
پیشنیاز: آشنایی با Python، NumPy و مفاهیم پایه شبکههای عصبی.
🔹 نصب و import
# نصب (در محیط واقعی)
# pip install tensorflow
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# بررسی نسخه و GPU
print(f"TensorFlow version: {tf.__version__}")
# بررسی وجود GPU
print("GPU Available:", tf.config.list_physical_devices('GPU'))
print("TensorFlow imported successfully!")
🔹 مفاهیم پایه: Tensor و Variable
import tensorflow as tf
import numpy as np
# ===== Tensor =====
# Tensor یک آرایه چندبعدی است (مشابه NumPy)
tensor_1d = tf.constant([1, 2, 3, 4, 5])
tensor_2d = tf.constant([[1, 2], [3, 4]])
tensor_3d = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("1D Tensor:", tensor_1d)
print("2D Tensor:\n", tensor_2d)
print("Shape:", tensor_2d.shape)
print("Dtype:", tensor_2d.dtype)
# ===== Variable =====
# Variable قابل تغییر است (برای وزنهای مدل)
w = tf.Variable(tf.random.normal([3, 3], mean=0.0, stddev=0.1))
b = tf.Variable(tf.zeros([3]))
print("\nWeight Variable:", w)
print("Bias Variable:", b)
# تبدیل Tensor به NumPy
numpy_array = tensor_1d.numpy()
print("\nNumPy array:", numpy_array)
🔹 Keras Sequential API
Sequential API سادهترین روش برای ساخت مدلهای لایهای است. این API برای مدلهایی که به صورت پشتهای از لایهها هستند، مناسب است [citation:5][citation:7].
import tensorflow as tf
from tensorflow.keras import layers
# ساخت مدل Sequential
model = tf.keras.Sequential([
layers.Flatten(input_shape=(28, 28)), # تبدیل تصویر 28x28 به بردار 784
layers.Dense(128, activation='relu'), # لایه پنهان با 128 نورون
layers.Dropout(0.2), # Dropout برای جلوگیری از overfitting
layers.Dense(10, activation='softmax') # خروجی 10 کلاس
])
# نمایش خلاصه مدل
model.summary()
# کامپایل مدل
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
print("\nModel compiled successfully!")
# مثال: پیشبینی با داده تصادفی
sample_input = tf.random.normal([1, 28, 28])
prediction = model(sample_input)
print(f"Prediction shape: {prediction.shape}")
print(f"Logits sample: {prediction[0][:5]}")
🔹 آموزش مدل با دیتاست MNIST
MNIST یک دیتاست کلاسیک شامل تصاویر دستنوشته اعداد ۰ تا ۹ است [citation:3][citation:5][citation:9].
import tensorflow as tf
from tensorflow.keras import layers
# بارگذاری دیتاست MNIST
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# نرمالسازی (مقیاسسازی به بازه 0 تا 1)
x_train = x_train / 255.0
x_test = x_test / 255.0
print(f"Train data shape: {x_train.shape}")
print(f"Train labels shape: {y_train.shape}")
print(f"Test data shape: {x_test.shape}")
print(f"Test labels shape: {y_test.shape}")
# نمایش یک نمونه تصویر
import matplotlib.pyplot as plt
plt.figure(figsize=(2, 2))
plt.imshow(x_train[0], cmap='gray')
plt.title(f"Label: {y_train[0]}")
plt.show()
# ===== ساخت مدل =====
model = tf.keras.Sequential([
layers.Flatten(input_shape=(28, 28)),
layers.Dense(128, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
# ===== کامپایل =====
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# ===== آموزش =====
history = model.fit(
x_train, y_train,
epochs=5,
validation_data=(x_test, y_test),
verbose=1
)
# ===== ارزیابی =====
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"\nTest accuracy: {test_acc:.4f}")
print(f"Test loss: {test_loss:.4f}")
🔹 لایههای پرکاربرد در Keras
import tensorflow as tf
from tensorflow.keras import layers
# ===== لایه Dense (Fully Connected) =====
# هر نورون به تمام نورونهای لایه قبل متصل است
dense_layer = layers.Dense(64, activation='relu')
print("Dense layer:", dense_layer)
# ===== لایه Conv2D (کانولوشن) =====
# برای پردازش تصاویر و دادههای فضایی
conv_layer = layers.Conv2D(32, (3, 3), activation='relu')
print("Conv2D layer:", conv_layer)
# ===== لایه MaxPooling2D =====
# کاهش ابعاد و استخراج ویژگیهای برجسته
pool_layer = layers.MaxPooling2D((2, 2))
print("MaxPooling2D layer:", pool_layer)
# ===== لایه Dropout =====
# جلوگیری از overfitting با غیرفعال کردن تصادفی نورونها
dropout_layer = layers.Dropout(0.5)
print("Dropout layer:", dropout_layer)
# ===== لایه Flatten =====
# تبدیل داده چندبعدی به یکبعدی
flatten_layer = layers.Flatten()
print("Flatten layer:", flatten_layer)
# ===== لایه Embedding =====
# برای دادههای دستهبندی (مانند کلمات)
embedding_layer = layers.Embedding(input_dim=1000, output_dim=64)
print("Embedding layer:", embedding_layer)
# ===== لایه LSTM =====
# برای دادههای دنبالهای (زمانی، متنی)
lstm_layer = layers.LSTM(64)
print("LSTM layer:", lstm_layer)
🔹 مدل CNN با دیتاست CIFAR-10
CIFAR-10 یک دیتاست شامل ۶۰,۰۰۰ تصویر رنگی ۳۲x۳۲ در ۱۰ کلاس است [citation:6].
import tensorflow as tf
from tensorflow.keras import layers
# بارگذاری دیتاست CIFAR-10
cifar10 = tf.keras.datasets.cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# نرمالسازی
x_train = x_train / 255.0
x_test = x_test / 255.0
# نام کلاسها
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
print(f"Train data shape: {x_train.shape}") # (50000, 32, 32, 3)
print(f"Test data shape: {x_test.shape}") # (10000, 32, 32, 3)
# ===== ساخت مدل CNN =====
model = tf.keras.Sequential([
# لایههای کانولوشن
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
# تبدیل به بردار
layers.Flatten(),
# لایههای Dense
layers.Dense(64, activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
# نمایش خلاصه مدل
model.summary()
# ===== کامپایل و آموزش =====
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
x_train, y_train,
epochs=5,
validation_data=(x_test, y_test),
verbose=1
)
# ===== ارزیابی =====
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"\nTest accuracy: {test_acc:.4f}")
🔹 مدل با Keras Functional API
Functional API برای مدلهای پیچیدهتر با چندین ورودی/خروجی و معماریهای غیرخطی مناسب است [citation:2][citation:7].
import tensorflow as tf
from tensorflow.keras import layers, Model
# ===== ورودی =====
inputs = layers.Input(shape=(28, 28))
# ===== شاخه اول =====
x1 = layers.Flatten()(inputs)
x1 = layers.Dense(128, activation='relu')(x1)
x1 = layers.Dropout(0.2)(x1)
output1 = layers.Dense(10, activation='softmax', name='main_output')(x1)
# ===== شاخه دوم (پیشبینی زوج/فرد) =====
x2 = layers.Flatten()(inputs)
x2 = layers.Dense(64, activation='relu')(x2)
x2 = layers.Dropout(0.2)(x2)
output2 = layers.Dense(2, activation='softmax', name='parity_output')(x2)
# ===== ساخت مدل با دو خروجی =====
model = Model(
inputs=inputs,
outputs=[output1, output2]
)
model.summary()
# ===== کامپایل با دو تابع ضرر =====
model.compile(
optimizer='adam',
loss={
'main_output': 'sparse_categorical_crossentropy',
'parity_output': 'sparse_categorical_crossentropy'
},
metrics={'main_output': 'accuracy', 'parity_output': 'accuracy'}
)
print("\nModel with multiple outputs compiled successfully!")
🔹 مدل با Keras Subclassing API
Subclassing API بیشترین انعطافپذیری را ارائه میدهد و برای تحقیقات و معماریهای سفارشی مناسب است [citation:9].
import tensorflow as tf
from tensorflow.keras import layers, Model
# ===== تعریف مدل با Subclassing =====
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = layers.Conv2D(32, 3, activation='relu')
self.flatten = layers.Flatten()
self.d1 = layers.Dense(128, activation='relu')
self.dropout = layers.Dropout(0.2)
self.d2 = layers.Dense(10)
def call(self, x, training=False):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
if training:
x = self.dropout(x)
return self.d2(x)
# ===== استفاده =====
model = MyModel()
# ورودی نمونه (تصویر 28x28 با یک کانال)
sample_input = tf.random.normal([1, 28, 28, 1])
output = model(sample_input, training=False)
print(f"Output shape: {output.shape}")
# نمایش خلاصه (برای Subclassing نیاز به build با ورودی مشخص دارد)
model.build(input_shape=(None, 28, 28, 1))
model.summary()
print("\nCustom model created successfully!")
🔹 ذخیره و بازیابی مدل
import tensorflow as tf
from tensorflow.keras import layers
import os
# ساخت یک مدل ساده
def create_simple_model():
return tf.keras.Sequential([
layers.Flatten(input_shape=(28, 28)),
layers.Dense(128, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
model = create_simple_model()
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# ===== ذخیره مدل =====
# روش ۱: ذخیره کامل مدل (وزنها + معماری + optimizer)
model.save('my_model.keras')
print("Model saved as 'my_model.keras'")
# روش ۲: ذخیره فقط وزنها
model.save_weights('my_model_weights.h5')
print("Weights saved as 'my_model_weights.h5'")
# ===== بازیابی مدل =====
# روش ۱: بارگذاری کامل
loaded_model = tf.keras.models.load_model('my_model.keras')
print("Model loaded from 'my_model.keras'")
# روش ۲: بارگذاری وزنها
new_model = create_simple_model()
new_model.load_weights('my_model_weights.h5')
print("Weights loaded from 'my_model_weights.h5'")
# ===== ذخیره در SavedModel =====
# برای استفاده در TensorFlow Serving
model.export('saved_model')
print("Model exported to 'saved_model'")
# حذف فایلهای موقت (در صورت وجود)
# os.remove('my_model.keras')
# os.remove('my_model_weights.h5')
🔹 Callbacks برای کنترل آموزش
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard
# بارگذاری داده MNIST
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
# ساخت مدل
model = tf.keras.Sequential([
layers.Flatten(input_shape=(28, 28)),
layers.Dense(128, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# ===== Callbacks =====
callbacks = [
# EarlyStopping: توقف آموزش در صورت عدم بهبود
EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True),
# ModelCheckpoint: ذخیره بهترین مدل
ModelCheckpoint('best_model.keras', monitor='val_accuracy', save_best_only=True),
# TensorBoard: ثبت لاگ برای TensorBoard
# TensorBoard(log_dir='./logs')
]
print("Callbacks defined:")
print(" - EarlyStopping: stops training when validation loss stops improving")
print(" - ModelCheckpoint: saves the best model based on validation accuracy")
# آموزش با Callbacks
history = model.fit(
x_train, y_train,
epochs=10,
validation_data=(x_test, y_test),
callbacks=callbacks,
verbose=1
)
print("\nTraining completed with callbacks!")
🔹 tf.data برای ورودی کارآمد
tf.data یک API قدرتمند برای ساخت pipelineهای ورودی با کارایی بالا است [citation:2][citation:3].
import tensorflow as tf
# ===== ایجاد دیتاست از NumPy =====
x_train = tf.random.normal([1000, 28, 28])
y_train = tf.random.uniform([1000], maxval=10, dtype=tf.int32)
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
print("Dataset from tensors:", dataset)
# ===== تبدیل و Batch =====
dataset = dataset.shuffle(1000) # اختلاط دادهها
dataset = dataset.batch(32) # دستهبندی
dataset = dataset.prefetch(tf.data.AUTOTUNE) # پیشبارگذاری
# ===== استفاده در آموزش =====
# model.fit(dataset, epochs=5)
# ===== مثال کامل با MNIST =====
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# نرمالسازی و ساخت دیتاست
train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_dataset = train_dataset.map(lambda x, y: (x / 255.0, y))
train_dataset = train_dataset.shuffle(60000).batch(64).prefetch(tf.data.AUTOTUNE)
# ساخت مدل ساده
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
print("Data pipeline created successfully!")
print(f"Dataset: {train_dataset}")
print("Ready for training with model.fit(dataset, epochs=5)")
🔹 مثال جامع: پیشبینی با TensorFlow
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
class DigitClassifier:
def __init__(self):
self.model = None
self.history = None
def build_model(self):
"""ساخت مدل"""
self.model = tf.keras.Sequential([
layers.Flatten(input_shape=(28, 28)),
layers.Dense(128, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
self.model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
return self.model
def train(self, x_train, y_train, x_test, y_test, epochs=5):
"""آموزش مدل"""
self.history = self.model.fit(
x_train, y_train,
epochs=epochs,
validation_data=(x_test, y_test),
verbose=1
)
return self.history
def evaluate(self, x_test, y_test):
"""ارزیابی مدل"""
test_loss, test_acc = self.model.evaluate(x_test, y_test, verbose=0)
print(f"Test accuracy: {test_acc:.4f}")
print(f"Test loss: {test_loss:.4f}")
return test_acc
def predict(self, image):
"""پیشبینی برای یک تصویر"""
if len(image.shape) == 2:
image = image.reshape(1, 28, 28)
predictions = self.model.predict(image)
return np.argmax(predictions[0]), np.max(predictions[0])
def show_history(self):
"""نمایش نمودارهای آموزش"""
if self.history is None:
print("Model not trained yet!")
return
# نمودار accuracy
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(self.history.history['accuracy'], label='Train')
plt.plot(self.history.history['val_accuracy'], label='Validation')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Model Accuracy')
# نمودار loss
plt.subplot(1, 2, 2)
plt.plot(self.history.history['loss'], label='Train')
plt.plot(self.history.history['val_loss'], label='Validation')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Model Loss')
plt.show()
# ===== استفاده =====
# بارگذاری داده
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# نرمالسازی
x_train_norm = x_train / 255.0
x_test_norm = x_test / 255.0
# ایجاد و آموزش مدل
classifier = DigitClassifier()
classifier.build_model()
print("Training model...")
classifier.train(x_train_norm, y_train, x_test_norm, y_test, epochs=5)
# ارزیابی
classifier.evaluate(x_test_norm, y_test)
# پیشبینی یک نمونه
sample_idx = 0
pred_class, confidence = classifier.predict(x_test[sample_idx])
print(f"\nSample prediction: {pred_class} (confidence: {confidence:.4f})")
print(f"True label: {y_test[sample_idx]}")
# نمایش نمودارها
classifier.show_history()
📌 نکات کلیدی
- ✅ Tensor آرایه چندبعدی پایه در TensorFlow است.
- ✅ Variable برای وزنهای قابل آموزش مدل استفاده میشود.
- ✅ Sequential API برای مدلهای پشتهای ساده است.
- ✅ Functional API برای مدلهای پیچیدهتر با چندین ورودی/خروجی [citation:2].
- ✅ Subclassing API بیشترین انعطافپذیری را برای تحقیقات فراهم میکند [citation:9].
- ✅ Dropout یک روش موثر برای جلوگیری از overfitting است [citation:3][citation:9].
- ✅ Callbacks مانند
EarlyStoppingوModelCheckpointکنترل بیشتری بر آموزش میدهند. - ✅ tf.data برای ایجاد pipelineهای ورودی کارآمد استفاده میشود [citation:2].
- ✅ مدلها را میتوان با
model.save()وtf.keras.models.load_model()ذخیره و بازیابی کرد. - ✅ TensorFlow از GPU و TPU برای تسریع آموزش پشتیبانی میکند [citation:8].