এমবেডিং ব্যবহার করে একটি টেক্সট ক্লাসিফায়ারকে প্রশিক্ষণ দেওয়া

ai.google.dev-এ দেখুন Google Colab-এ চালান GitHub-এ উৎস দেখুন

ওভারভিউ

এই নোটবুকে, আপনি একটি মডেলকে প্রশিক্ষণ দিতে Gemini API দ্বারা উত্পাদিত এমবেডিংগুলি ব্যবহার করতে শিখবেন যা বিষয়ের উপর ভিত্তি করে বিভিন্ন ধরণের নিউজগ্রুপ পোস্টগুলিকে শ্রেণীবদ্ধ করতে পারে৷

এই টিউটোরিয়ালে, নিউজগ্রুপ পোস্ট কোন শ্রেণীর অন্তর্গত তা ভবিষ্যদ্বাণী করার জন্য আপনি একটি শ্রেণিবিন্যাসকারীকে প্রশিক্ষণ দেবেন।

পূর্বশর্ত

আপনি Google Colab-এ এই কুইকস্টার্ট চালাতে পারেন।

আপনার নিজের বিকাশের পরিবেশে এই দ্রুত সূচনাটি সম্পূর্ণ করতে, নিশ্চিত করুন যে আপনার পরিবেশ নিম্নলিখিত প্রয়োজনীয়তাগুলি পূরণ করে:

  • Python 3.9+
  • নোটবুক চালানোর জন্য jupyter একটি ইনস্টলেশন।

সেটআপ

প্রথমে, জেমিনি API পাইথন লাইব্রেরি ডাউনলোড এবং ইনস্টল করুন।

pip install -U -q google.generativeai
import re
import tqdm
import keras
import numpy as np
import pandas as pd

import google.generativeai as genai
import google.ai.generativelanguage as glm

# Used to securely store your API key
from google.colab import userdata

import seaborn as sns
import matplotlib.pyplot as plt

from keras import layers
from matplotlib.ticker import MaxNLocator
from sklearn.datasets import fetch_20newsgroups
import sklearn.metrics as skmetrics

একটি API কী ধরুন

আপনি Gemini API ব্যবহার করার আগে, আপনাকে প্রথমে একটি API কী পেতে হবে। যদি আপনার কাছে ইতিমধ্যে একটি না থাকে তবে Google AI স্টুডিওতে এক ক্লিকে একটি কী তৈরি করুন৷

একটি API কী পান

Colab-এ, বাঁদিকের প্যানেলে "🔑"-এর নিচে সিক্রেট ম্যানেজারের কী যোগ করুন। এটিকে API_KEY নাম দিন।

একবার আপনার কাছে API কী হয়ে গেলে, এটি SDK-এ পাস করুন। আপনি এটি দুটি উপায়ে করতে পারেন:

  • কীটি GOOGLE_API_KEY এনভায়রনমেন্ট ভেরিয়েবলে রাখুন (SDK স্বয়ংক্রিয়ভাবে সেখান থেকে তুলে নেবে)।
  • genai.configure(api_key=...) এ কী পাস করুন
# Or use `os.getenv('API_KEY')` to fetch an environment variable.
API_KEY=userdata.get('API_KEY')

genai.configure(api_key=API_KEY)
for m in genai.list_models():
  if 'embedContent' in m.supported_generation_methods:
    print(m.name)
models/embedding-001
models/embedding-001

ডেটাসেট

20টি নিউজগ্রুপ টেক্সট ডেটাসেটে 20টি বিষয়ের উপর 18,000টি নিউজগ্রুপ পোস্ট রয়েছে যা প্রশিক্ষণ এবং পরীক্ষার সেটে বিভক্ত। প্রশিক্ষণ এবং পরীক্ষার ডেটাসেটের মধ্যে বিভাজন একটি নির্দিষ্ট তারিখের আগে এবং পরে পোস্ট করা বার্তাগুলির উপর ভিত্তি করে। এই টিউটোরিয়ালের জন্য, আপনি প্রশিক্ষণ এবং পরীক্ষার ডেটাসেটের উপসেটগুলি ব্যবহার করবেন। আপনি পান্ডাস ডেটাফ্রেমে ডেটা প্রিপ্রসেস এবং সংগঠিত করবেন।

newsgroups_train = fetch_20newsgroups(subset='train')
newsgroups_test = fetch_20newsgroups(subset='test')

# View list of class names for dataset
newsgroups_train.target_names
['alt.atheism',
 'comp.graphics',
 'comp.os.ms-windows.misc',
 'comp.sys.ibm.pc.hardware',
 'comp.sys.mac.hardware',
 'comp.windows.x',
 'misc.forsale',
 'rec.autos',
 'rec.motorcycles',
 'rec.sport.baseball',
 'rec.sport.hockey',
 'sci.crypt',
 'sci.electronics',
 'sci.med',
 'sci.space',
 'soc.religion.christian',
 'talk.politics.guns',
 'talk.politics.mideast',
 'talk.politics.misc',
 'talk.religion.misc']

প্রশিক্ষণ সেট থেকে একটি ডেটা পয়েন্ট কেমন দেখায় তার একটি উদাহরণ এখানে।

idx = newsgroups_train.data[0].index('Lines')
print(newsgroups_train.data[0][idx:])
Lines: 15

 I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is 
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,

- IL
   ---- brought to you by your neighborhood Lerxst ----

এখন আপনি এই টিউটোরিয়ালের জন্য ডেটা প্রিপ্রসেস করা শুরু করবেন। নাম, ইমেল বা পাঠ্যের অপ্রয়োজনীয় অংশ যেমন "From: " এবং "\nSubject: " এর মতো যেকোনো সংবেদনশীল তথ্য সরান। তথ্যটিকে একটি পান্ডাস ডেটাফ্রেমে সংগঠিত করুন যাতে এটি আরও পাঠযোগ্য হয়।

def preprocess_newsgroup_data(newsgroup_dataset):
  # Apply functions to remove names, emails, and extraneous words from data points in newsgroups.data
  newsgroup_dataset.data = [re.sub(r'[\w\.-]+@[\w\.-]+', '', d) for d in newsgroup_dataset.data] # Remove email
  newsgroup_dataset.data = [re.sub(r"\([^()]*\)", "", d) for d in newsgroup_dataset.data] # Remove names
  newsgroup_dataset.data = [d.replace("From: ", "") for d in newsgroup_dataset.data] # Remove "From: "
  newsgroup_dataset.data = [d.replace("\nSubject: ", "") for d in newsgroup_dataset.data] # Remove "\nSubject: "

  # Cut off each text entry after 5,000 characters
  newsgroup_dataset.data = [d[0:5000] if len(d) > 5000 else d for d in newsgroup_dataset.data]

  # Put data points into dataframe
  df_processed = pd.DataFrame(newsgroup_dataset.data, columns=['Text'])
  df_processed['Label'] = newsgroup_dataset.target
  # Match label to target name index
  df_processed['Class Name'] = ''
  for idx, row in df_processed.iterrows():
    df_processed.at[idx, 'Class Name'] = newsgroup_dataset.target_names[row['Label']]

  return df_processed
# Apply preprocessing function to training and test datasets
df_train = preprocess_newsgroup_data(newsgroups_train)
df_test = preprocess_newsgroup_data(newsgroups_test)

df_train.head()

এরপর, আপনি প্রশিক্ষণ ডেটাসেটে 100টি ডেটা পয়েন্ট নিয়ে এবং এই টিউটোরিয়ালটি চালানোর জন্য কয়েকটি বিভাগ বাদ দিয়ে কিছু ডেটার নমুনা নেবেন। তুলনা করার জন্য বিজ্ঞান বিভাগগুলি বেছে নিন।

def sample_data(df, num_samples, classes_to_keep):
  df = df.groupby('Label', as_index = False).apply(lambda x: x.sample(num_samples)).reset_index(drop=True)

  df = df[df['Class Name'].str.contains(classes_to_keep)]

  # Reset the encoding of the labels after sampling and dropping certain categories
  df['Class Name'] = df['Class Name'].astype('category')
  df['Encoded Label'] = df['Class Name'].cat.codes

  return df
TRAIN_NUM_SAMPLES = 100
TEST_NUM_SAMPLES = 25
CLASSES_TO_KEEP = 'sci' # Class name should contain 'sci' in it to keep science categories
df_train = sample_data(df_train, TRAIN_NUM_SAMPLES, CLASSES_TO_KEEP)
df_test = sample_data(df_test, TEST_NUM_SAMPLES, CLASSES_TO_KEEP)
df_train.value_counts('Class Name')
Class Name
sci.crypt          100
sci.electronics    100
sci.med            100
sci.space          100
dtype: int64
df_test.value_counts('Class Name')
Class Name
sci.crypt          25
sci.electronics    25
sci.med            25
sci.space          25
dtype: int64

এমবেডিং তৈরি করুন

এই বিভাগে, আপনি Gemini API থেকে এমবেডিং ব্যবহার করে পাঠ্যের একটি অংশের জন্য এমবেডিং তৈরি করতে দেখতে পাবেন। এম্বেডিং সম্পর্কে আরও জানতে, এম্বেডিং গাইড দেখুন।

এম্বেডিং এম্বেডিং-001 এ API পরিবর্তন

নতুন এম্বেডিং মডেলের জন্য, একটি নতুন টাস্ক টাইপ প্যারামিটার এবং ঐচ্ছিক শিরোনাম রয়েছে (শুধুমাত্র task_type= RETRIEVAL_DOCUMENT এর সাথে বৈধ)।

এই নতুন প্যারামিটারগুলি শুধুমাত্র নতুন এমবেডিং মডেলগুলিতে প্রযোজ্য৷ টাস্কের ধরনগুলি হল:

টাস্ক টাইপ বর্ণনা
RETRIEVAL_QUERY প্রদত্ত টেক্সট একটি অনুসন্ধান/পুনরুদ্ধার সেটিং একটি ক্যোয়ারী নির্দিষ্ট করে.
RETRIEVAL_DOCUMENT প্রদত্ত পাঠ্যটি একটি অনুসন্ধান/পুনরুদ্ধার সেটিং এর একটি নথি নির্দিষ্ট করে৷
SEMANTIC_SIMILARITY প্রদত্ত টেক্সট শব্দার্থিক টেক্সচুয়াল সাদৃশ্য (STS) এর জন্য ব্যবহার করা হবে তা নির্দিষ্ট করে।
শ্রেণীবিভাগ নির্দিষ্ট করে যে এমবেডিংগুলি শ্রেণীবিভাগের জন্য ব্যবহার করা হবে৷
ক্লাস্টারিং নির্দিষ্ট করে যে এমবেডিংগুলি ক্লাস্টারিংয়ের জন্য ব্যবহার করা হবে৷
from tqdm.auto import tqdm
tqdm.pandas()

from google.api_core import retry

def make_embed_text_fn(model):

  @retry.Retry(timeout=300.0)
  def embed_fn(text: str) -> list[float]:
    # Set the task_type to CLASSIFICATION.
    embedding = genai.embed_content(model=model,
                                    content=text,
                                    task_type="classification")
    return embedding['embedding']

  return embed_fn

def create_embeddings(model, df):
  df['Embeddings'] = df['Text'].progress_apply(make_embed_text_fn(model))
  return df
model = 'models/embedding-001'
df_train = create_embeddings(model, df_train)
df_test = create_embeddings(model, df_test)
0%|          | 0/400 [00:00<?, ?it/s]
0%|          | 0/100 [00:00<?, ?it/s]
df_train.head()

একটি সাধারণ শ্রেণিবিন্যাস মডেল তৈরি করুন

এখানে আপনি একটি লুকানো স্তর এবং একটি একক শ্রেণীর সম্ভাব্যতা আউটপুট সহ একটি সাধারণ মডেল সংজ্ঞায়িত করবেন। ভবিষ্যদ্বাণীটি পাঠ্যের একটি অংশের একটি নির্দিষ্ট শ্রেণীর সংবাদ হওয়ার সম্ভাবনার সাথে মিলে যাবে। আপনি যখন আপনার মডেল তৈরি করবেন, কেরাস স্বয়ংক্রিয়ভাবে ডেটা পয়েন্টগুলিকে এলোমেলো করবে।

def build_classification_model(input_size: int, num_classes: int) -> keras.Model:
  inputs = x = keras.Input(input_size)
  x = layers.Dense(input_size, activation='relu')(x)
  x = layers.Dense(num_classes, activation='sigmoid')(x)
  return keras.Model(inputs=[inputs], outputs=x)
# Derive the embedding size from the first training element.
embedding_size = len(df_train['Embeddings'].iloc[0])

# Give your model a different name, as you have already used the variable name 'model'
classifier = build_classification_model(embedding_size, len(df_train['Class Name'].unique()))
classifier.summary()

classifier.compile(loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                   optimizer = keras.optimizers.Adam(learning_rate=0.001),
                   metrics=['accuracy'])
Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_1 (InputLayer)        [(None, 768)]             0         
                                                                 
 dense (Dense)               (None, 768)               590592    
                                                                 
 dense_1 (Dense)             (None, 4)                 3076      
                                                                 
=================================================================
Total params: 593668 (2.26 MB)
Trainable params: 593668 (2.26 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
embedding_size
768

নিউজগ্রুপ শ্রেণীবদ্ধ করার জন্য মডেলকে প্রশিক্ষণ দিন

অবশেষে, আপনি একটি সাধারণ মডেল প্রশিক্ষণ দিতে পারেন। ওভারফিটিং এড়াতে অল্প সংখ্যক যুগ ব্যবহার করুন। প্রথম যুগটি বাকিগুলির তুলনায় অনেক বেশি সময় নেয়, কারণ এমবেডিংগুলি শুধুমাত্র একবার গণনা করা প্রয়োজন৷

NUM_EPOCHS = 20
BATCH_SIZE = 32

# Split the x and y components of the train and validation subsets.
y_train = df_train['Encoded Label']
x_train = np.stack(df_train['Embeddings'])
y_val = df_test['Encoded Label']
x_val = np.stack(df_test['Embeddings'])

# Train the model for the desired number of epochs.
callback = keras.callbacks.EarlyStopping(monitor='accuracy', patience=3)

history = classifier.fit(x=x_train,
                         y=y_train,
                         validation_data=(x_val, y_val),
                         callbacks=[callback],
                         batch_size=BATCH_SIZE,
                         epochs=NUM_EPOCHS,)
Epoch 1/20
/usr/local/lib/python3.10/dist-packages/keras/src/backend.py:5729: UserWarning: "`sparse_categorical_crossentropy` received `from_logits=True`, but the `output` argument was produced by a Softmax activation and thus does not represent logits. Was this intended?
  output, from_logits = _get_logits(
13/13 [==============================] - 1s 30ms/step - loss: 1.2141 - accuracy: 0.6675 - val_loss: 0.9801 - val_accuracy: 0.8800
Epoch 2/20
13/13 [==============================] - 0s 12ms/step - loss: 0.7580 - accuracy: 0.9400 - val_loss: 0.6061 - val_accuracy: 0.9300
Epoch 3/20
13/13 [==============================] - 0s 13ms/step - loss: 0.4249 - accuracy: 0.9525 - val_loss: 0.3902 - val_accuracy: 0.9200
Epoch 4/20
13/13 [==============================] - 0s 13ms/step - loss: 0.2561 - accuracy: 0.9625 - val_loss: 0.2597 - val_accuracy: 0.9400
Epoch 5/20
13/13 [==============================] - 0s 13ms/step - loss: 0.1693 - accuracy: 0.9700 - val_loss: 0.2145 - val_accuracy: 0.9300
Epoch 6/20
13/13 [==============================] - 0s 13ms/step - loss: 0.1240 - accuracy: 0.9850 - val_loss: 0.1801 - val_accuracy: 0.9600
Epoch 7/20
13/13 [==============================] - 0s 21ms/step - loss: 0.0931 - accuracy: 0.9875 - val_loss: 0.1623 - val_accuracy: 0.9400
Epoch 8/20
13/13 [==============================] - 0s 16ms/step - loss: 0.0736 - accuracy: 0.9925 - val_loss: 0.1418 - val_accuracy: 0.9600
Epoch 9/20
13/13 [==============================] - 0s 20ms/step - loss: 0.0613 - accuracy: 0.9925 - val_loss: 0.1315 - val_accuracy: 0.9700
Epoch 10/20
13/13 [==============================] - 0s 20ms/step - loss: 0.0479 - accuracy: 0.9975 - val_loss: 0.1235 - val_accuracy: 0.9600
Epoch 11/20
13/13 [==============================] - 0s 19ms/step - loss: 0.0399 - accuracy: 0.9975 - val_loss: 0.1219 - val_accuracy: 0.9700
Epoch 12/20
13/13 [==============================] - 0s 21ms/step - loss: 0.0326 - accuracy: 0.9975 - val_loss: 0.1158 - val_accuracy: 0.9700
Epoch 13/20
13/13 [==============================] - 0s 19ms/step - loss: 0.0263 - accuracy: 1.0000 - val_loss: 0.1127 - val_accuracy: 0.9700
Epoch 14/20
13/13 [==============================] - 0s 17ms/step - loss: 0.0229 - accuracy: 1.0000 - val_loss: 0.1123 - val_accuracy: 0.9700
Epoch 15/20
13/13 [==============================] - 0s 20ms/step - loss: 0.0195 - accuracy: 1.0000 - val_loss: 0.1063 - val_accuracy: 0.9700
Epoch 16/20
13/13 [==============================] - 0s 17ms/step - loss: 0.0172 - accuracy: 1.0000 - val_loss: 0.1070 - val_accuracy: 0.9700

মডেল কর্মক্ষমতা মূল্যায়ন

পরীক্ষার ডেটাসেটের ক্ষতি এবং নির্ভুলতা পেতে Keras Model.evaluate ব্যবহার করুন।

classifier.evaluate(x=x_val, y=y_val, return_dict=True)
4/4 [==============================] - 0s 4ms/step - loss: 0.1070 - accuracy: 0.9700
{'loss': 0.10700511932373047, 'accuracy': 0.9700000286102295}

আপনার মডেল পারফরম্যান্স মূল্যায়ন করার একটি উপায় হল ক্লাসিফায়ার পারফরম্যান্সকে কল্পনা করা। যুগে ক্ষতি এবং নির্ভুলতার প্রবণতা দেখতে plot_history ব্যবহার করুন।

def plot_history(history):
  """
    Plotting training and validation learning curves.

    Args:
      history: model history with all the metric measures
  """
  fig, (ax1, ax2) = plt.subplots(1,2)
  fig.set_size_inches(20, 8)

  # Plot loss
  ax1.set_title('Loss')
  ax1.plot(history.history['loss'], label = 'train')
  ax1.plot(history.history['val_loss'], label = 'test')
  ax1.set_ylabel('Loss')

  ax1.set_xlabel('Epoch')
  ax1.legend(['Train', 'Validation'])

  # Plot accuracy
  ax2.set_title('Accuracy')
  ax2.plot(history.history['accuracy'],  label = 'train')
  ax2.plot(history.history['val_accuracy'], label = 'test')
  ax2.set_ylabel('Accuracy')
  ax2.set_xlabel('Epoch')
  ax2.legend(['Train', 'Validation'])

  plt.show()

plot_history(history)

png

শুধুমাত্র ক্ষতি এবং নির্ভুলতা পরিমাপ করার বাইরে মডেলের কর্মক্ষমতা দেখার আরেকটি উপায় হল একটি বিভ্রান্তি ম্যাট্রিক্স ব্যবহার করা। বিভ্রান্তি ম্যাট্রিক্স আপনাকে নির্ভুলতার বাইরে শ্রেণীবিভাগ মডেলের কার্যকারিতা মূল্যায়ন করতে দেয়। আপনি দেখতে পারেন কি ভুল শ্রেণীবদ্ধ পয়েন্ট হিসাবে শ্রেণীবদ্ধ করা হয়. এই মাল্টি-ক্লাস শ্রেণীবিভাগ সমস্যার জন্য বিভ্রান্তি ম্যাট্রিক্স তৈরি করতে, পরীক্ষার সেটে প্রকৃত মান এবং পূর্বাভাসিত মানগুলি পান।

Model.predict() ব্যবহার করে বৈধতা সেটে প্রতিটি উদাহরণের জন্য ভবিষ্যদ্বাণী করা ক্লাস তৈরি করে শুরু করুন।

y_hat = classifier.predict(x=x_val)
y_hat = np.argmax(y_hat, axis=1)
4/4 [==============================] - 0s 4ms/step
labels_dict = dict(zip(df_test['Class Name'], df_test['Encoded Label']))
labels_dict
{'sci.crypt': 0, 'sci.electronics': 1, 'sci.med': 2, 'sci.space': 3}
cm = skmetrics.confusion_matrix(y_val, y_hat)
disp = skmetrics.ConfusionMatrixDisplay(confusion_matrix=cm,
                              display_labels=labels_dict.keys())
disp.plot(xticks_rotation='vertical')
plt.title('Confusion matrix for newsgroup test dataset');
plt.grid(False)

png

পরবর্তী পদক্ষেপ

আপনি কীভাবে এমবেডিং ব্যবহার করতে পারেন সে সম্পর্কে আরও জানতে, উপলব্ধ উদাহরণগুলি দেখুন। Gemini API-এ অন্যান্য পরিষেবাগুলি কীভাবে ব্যবহার করবেন তা জানতে, Python quickstart-এ যান।