एम्बेडिंग का इस्तेमाल करके टेक्स्ट क्लासिफ़ायर को ट्रेनिंग देना

ai.google.dev पर देखें Google Colab में चलाएं GitHub पर सोर्स देखें

खास जानकारी

इस notebook में, आप एक मॉडल को ट्रेनिंग देने के लिए Gemini API की मदद से तैयार किए गए एम्बेडिंग का इस्तेमाल करेंगे. यह मॉडल, विषय के आधार पर अलग-अलग तरह की न्यूज़ग्रुप पोस्ट की कैटगरी तय कर सकता है.

इस ट्यूटोरियल में, क्लासिफ़ायर को यह अनुमान लगाने की ट्रेनिंग दी जाएगी कि कोई न्यूज़ग्रुप पोस्ट किस क्लास से जुड़ी है.

ज़रूरी शर्तें

इस क्विकस्टार्ट को Google Colab में चलाया जा सकता है.

अपने डेवलपमेंट एनवायरमेंट में इस क्विकस्टार्ट को पूरा करने के लिए, पक्का करें कि आपका माहौल इन शर्तों को पूरा करता हो:

  • Python 3.9 और इसके बाद के वर्शन
  • notebook चलाने के लिए jupyter का इंस्टॉलेशन.

सेटअप

सबसे पहले, Gemini API Python लाइब्रेरी को डाउनलोड और इंस्टॉल करें.

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 का इस्तेमाल करने से पहले, आपको एपीआई पासकोड हासिल करना होगा. अगर आपके पास पहले से कोई कुंजी नहीं है, तो Google AI Studio में सिर्फ़ एक क्लिक करके कुंजी बनाएं.

एपीआई पासकोड पाएं

Colab में, सीक्रेट मैनेजर में बाईं ओर मौजूद पैनल में " दिलचस्पी" में जाकर कुंजी जोड़ें. इसे API_KEY नाम दें.

एपीआई पासकोड मिलने के बाद, उसे 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 न्यूज़ग्रुप पोस्ट हैं. इन्हें ट्रेनिंग और टेस्ट सेट में बांटा गया है. ट्रेनिंग और टेस्ट डेटासेट के बीच फ़र्क़, किसी खास तारीख से पहले और बाद में पोस्ट किए गए मैसेज के आधार पर तय होता है. इस ट्यूटोरियल में ट्रेनिंग और टेस्ट डेटासेट के सबसेट का इस्तेमाल किया जाएगा. आपको Pandas डेटाफ़्रेम में डेटा को प्रीप्रोसेस और व्यवस्थित करना होगा.

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: " को हटा दें. जानकारी को Pandas डेटाफ़्रेम में व्यवस्थित करें, ताकि उसे आसानी से पढ़ा जा सके.

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 में एपीआई में हुए बदलाव

एम्बेड करने वाले नए मॉडल के लिए, एक नया टास्क टाइप पैरामीटर और वैकल्पिक शीर्षक मौजूद है (सिर्फ़ Task_type=RETRIEVAL_DOCUMENT के साथ मान्य है).

ये नए पैरामीटर सिर्फ़ एम्बेड किए गए नए मॉडल पर लागू होते हैं.ये टास्क इस तरह के हैं:

टास्क किस तरह का है ब्यौरा
RETRIEVAL_QUERY तय करता है कि दिया गया टेक्स्ट किसी खोज/उपयोगकर्ता हासिल करने की सेटिंग में मौजूद क्वेरी है.
RETRIEVAL_DOCUMENT तय करता है कि दिया गया टेक्स्ट खोज/वापस पाने की सेटिंग में मौजूद एक दस्तावेज़ है.
SEMANTIC_SIMILARITY इससे यह तय होता है कि दिए गए टेक्स्ट का इस्तेमाल सिमैंटिक टेक्स्ट वाली समानता (एसटीएस) के लिए किया जाएगा.
कैटगरी तय करना इससे यह पता चलता है कि एम्बेड किए गए लिंक का इस्तेमाल, कैटगरी तय करने के लिए किया जाएगा.
क्लस्टरिंग इससे यह पता चलता है कि एम्बेड किए गए लिंक का इस्तेमाल, क्लस्टरिंग के लिए किया जाएगा.
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()

आसान क्लासिफ़िकेशन मॉडल बनाना

यहां आपको एक सामान्य मॉडल बनाना होगा, जिसमें एक छिपी हुई लेयर और सिंगल क्लास प्रॉबबिलिटी आउटपुट शामिल होगा. यह अनुमान, टेक्स्ट के किसी हिस्से के खबरों का खास वर्ग होने की संभावना के हिसाब से होगा. मॉडल बनाने पर, Keras डेटा पॉइंट को अपने-आप शफ़ल कर देगा.

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

समाचार समूहों की कैटगरी तय करने के लिए मॉडल को ट्रेनिंग देना

आखिर में, एक आसान मॉडल को ट्रेनिंग दी जा सकती है. ओवरफ़िटिंग से बचने के लिए, epoch की कम संख्या का इस्तेमाल करें. पहले epoch में, बाकी पीरियड के मुकाबले ज़्यादा समय लगता है, क्योंकि एम्बेड करने की प्रोसेस सिर्फ़ एक बार करनी होती है.

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 क्विकस्टार्ट पर जाएं.