<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Odilbek Tokhirov on Medium]]></title>
        <description><![CDATA[Stories by Odilbek Tokhirov on Medium]]></description>
        <link>https://medium.com/@odil.tokhirov?source=rss-11ba1eecac62------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PiSkrHewOLXOfBoTm9MfzA.jpeg</url>
            <title>Stories by Odilbek Tokhirov on Medium</title>
            <link>https://medium.com/@odil.tokhirov?source=rss-11ba1eecac62------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:51:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@odil.tokhirov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 4)]]></title>
            <link>https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-4-0b2c2004eaf5?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b2c2004eaf5</guid>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 09:32:08 GMT</pubDate>
            <atom:updated>2024-01-07T09:32:08.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 4)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKNyc7P1SOHakaTKlf_PGg.png" /></figure><p>If you haven’t read the previous posts, I suggest you read them first:</p><ol><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-1-c53b1b087795">Part 1</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-2-d9cc360d81ab">Part 2</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-3-95b418c595ff">Part 3</a></li></ol><p>We stopped after training BERT on DAIGT-V2, MISTRAL-7B, and manually collected data in the last post. In this post, we will try experimenting with the model by changing various hyperparameters. We will also try new approaches such as predicting with multiple models at once and correcting typos in the essays.</p><h4>Table of Contents</h4><p>· <a href="#3e42">Continuing with the BERT model </a><br>· <a href="#0577">Returning to Gradient Boosting</a><br>· <a href="#5eb9">Hyperparameter configurations</a><br>· <a href="#e006">Using corrupted data</a><br>· <a href="#f1df">Using Voting Classifier</a><br>· <a href="#5a4d">Correcting spelling errors</a><br>· <a href="#c995">Conclusion</a></p><h3>Continuing with the BERT model</h3><p>I made another submission with the BERT model trained on the new data without the prompt_id feature. Only essays having prompts that were part of the competition’s hidden test set were included. To achieve that, I just filtered RDizzl3_seven values to be True. I also reduced the number of epochs to 30 since the training was taking too long.</p><pre>import pandas as pd<br>import tensorflow as tf<br>import tensorflow_hub as hub<br>import tensorflow_text as text<br>from sklearn.model_selection import train_test_split<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)  # all generated<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]  # remove False ones<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br><br>X_train, X_val, y_train, y_val = train_test_split(all_data[&#39;text&#39;], all_data[&#39;generated&#39;],<br>                                                  stratify=all_data[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br><br>preprocessor_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_preprocessor&quot;)<br>encoder_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_encoder&quot;)<br><br># Build the neural network<br>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=&#39;text_input&#39;)<br>encoder_inputs_bert = preprocessor_bert(text_input)<br>outputs_bert = encoder_bert(encoder_inputs_bert)<br><br>layer = tf.keras.layers.Dropout(0.2)(outputs_bert[&#39;pooled_output&#39;])<br>layer = tf.keras.layers.Dense(10, activation=&#39;relu&#39;)(layer)<br>layer = tf.keras.layers.Dropout(0.2)(layer)<br>layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(layer)  # sentence embedding<br><br>model = tf.keras.Model(inputs=[text_input], outputs=[layer])<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;,<br>    patience=5,<br>    restore_best_weights=True,<br>)<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[tf.keras.metrics.BinaryAccuracy(),<br>                       tf.keras.metrics.Precision(),<br>                       tf.keras.metrics.Recall()])<br><br>model.fit(X_train,<br>          y_train, epochs=30,<br>          validation_data=(X_val, y_val),<br>          callbacks=[early_stopping])<br><br>test_set = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = test_set[&#39;text&#39;]<br>y_pred = pd.Series(model.predict(X_test).flatten(), name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_set.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSKJebVCPQ9bQ6a-fD220A.png" /></figure><p>A score of 0.732 was obtained, a minimal increase over the best previous score of 0.731.</p><p>Next, I resubmitted the same code after modifying it to include the prompt_id feature just to see what would happen.</p><pre>import pandas as pd<br>import tensorflow as tf<br>import tensorflow_hub as hub<br>import tensorflow_text as text<br>from sklearn.model_selection import train_test_split<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)  # all generated<br><br>prompt_name_list = [&#39;Car-free cities&#39;, &#39;Does the electoral college work?&#39;, &#39;Facial action coding system&#39;,                     &#39;Driverless cars&#39;, &#39;Exploring Venus&#39;, &#39;&quot;A Cowboy Who Rode the Waves&quot;&#39;, &#39;The Face on Mars&#39;]<br>prompt_name_to_id = {k: v for v, k in enumerate(prompt_name_list)}<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br>daigt[&#39;prompt_id&#39;] = daigt[&#39;prompt_name&#39;].map(prompt_name_to_id)<br><br>mistral.drop([&#39;prompt_id&#39;], inplace=True, axis=1)<br>mistral[&#39;prompt_name&#39;].replace(&#39;A Cowboy Who Rode the Waves&#39;, &#39;&quot;A Cowboy Who Rode the Waves&quot;&#39;, inplace=True)<br>mistral[&#39;prompt_id&#39;] = mistral[&#39;prompt_name&#39;].map(prompt_name_to_id)<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;prompt_id&#39;, &#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br>    <br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br><br>X_train, X_val, y_train, y_val = train_test_split(all_data[[&#39;prompt_id&#39;, &#39;text&#39;]], all_data[&#39;generated&#39;],<br>                                                  stratify=all_data[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br><br>X_train = dict(X_train)<br>X_val = dict(X_val)<br><br>preprocessor_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_preprocessor&quot;)<br>encoder_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_encoder&quot;)<br><br># Build the neural network<br>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=&#39;text&#39;)<br>encoder_inputs_bert = preprocessor_bert(text_input)<br>outputs_bert = encoder_bert(encoder_inputs_bert)<br><br>prompt_id_input = tf.keras.layers.Input(shape=(), dtype=tf.float32, name=&#39;prompt_id&#39;)<br>concatenated_input = tf.keras.layers.Concatenate()([outputs_bert[&#39;pooled_output&#39;],  # includes prompt_id<br>                                                     tf.expand_dims(prompt_id_input, axis=-1)])<br><br>layer = tf.keras.layers.Dropout(0.2)(concatenated_input)<br>layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(layer)<br><br>model = tf.keras.Model(inputs=[prompt_id_input, text_input], outputs=[layer])<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;,<br>    patience=5,<br>    restore_best_weights=True,<br>)<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[tf.keras.metrics.BinaryAccuracy(),<br>                       tf.keras.metrics.Precision(),<br>                       tf.keras.metrics.Recall()])<br><br>model.fit(X_train,<br>          y_train, epochs=30,<br>          validation_data=(X_val, y_val),<br>          callbacks=[early_stopping])<br><br>test_set = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = dict(test_set[[&#39;prompt_id&#39;, &#39;text&#39;]])<br>y_pred = pd.Series(model.predict(X_test).flatten(), name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_set.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4uiKmzjcPctz4FbYa8pCA.png" /></figure><p>A worse score of 0.727 was obtained. I don’t think including that feature is a good idea as it has been consistently dropping the scores.</p><h3>Returning to Gradient Boosting</h3><p>I have decided to try the gradient boosting model again on the new data to check if we get a better result. This time, however, I used the XGBoost version. As before, we will first need a numeric representation. To do that, we can try TF-IDF. When I tried using it, an error message appeared stating: Your notebook tried to allocate more memory than is available. It has restarted. As a reminder, TF-IDF makes a new column for each unique word. Since not all of the words will be present in one essay, a sizeable portion of a row (feature vector) will consist of 0’s. This takes up a lot of memory. Therefore, I switched to using word2vec text representation instead as it produces vectors of fixed length, in our case 300. Next, text preprocessing was performed to remove punctuations and stop words, and to lemmatize the text for a cleaner form of data.</p><pre>import spacy<br>import pandas as pd<br>from xgboost import XGBClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import classification_report<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, and lemmatizes the tokens.&#39;&#39;&#39;<br>    doc = nlp(text)   <br>    return &#39; &#39;.join([token.lemma_ for token in doc if not token.is_punct and not token.is_stop])<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)  # all generated<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br>del daigt, mistral, mine<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: DataFrame(s) with word2vec representation of shape (n_samples, 300) along with &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    df[&#39;word2vec_doc&#39;] = df[&#39;processed_text&#39;].apply(lambda text: nlp(text).vector)<br>    df.drop(&#39;processed_text&#39;, axis=1, inplace=True)<br><br>    if &#39;generated&#39; in df.columns.values:<br>        X_train, X_val, y_train, y_val = train_test_split(df[&#39;word2vec_doc&#39;], df[&#39;generated&#39;],<br>                                                  stratify=df[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br><br>        X_train = X_train.apply(pd.Series)<br>        X_val = X_val.apply(pd.Series)<br>        <br>        return X_train, X_val, y_train, y_val<br>    <br>    # This is for X_test.<br>    return df[&#39;word2vec_doc&#39;].apply(pd.Series)<br><br>X_train, X_val, y_train, y_val = data_pipeline(all_data)<br><br>model = XGBClassifier(objective=&#39;binary:logistic&#39;)<br>model.fit(X_train, y_train, eval_metric=&quot;logloss&quot;, eval_set=[(X_val, y_val)], verbose=True)<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_data)<br>y_test_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_data.id, y_test_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlPQiAkD6VvNsmphFAyFhw.png" /></figure><p>The new score was 0.788, the highest so far. Training the XGBoost model took far less than training BERT.</p><p>For further experimentation, I decided to include all values from RDizzl3_seven feature to the above implementation.</p><pre>import spacy<br>import pandas as pd<br>from xgboost import XGBClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import classification_report<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, and lemmatizes the tokens.&#39;&#39;&#39;<br>    doc = nlp(text)   <br>    return &#39; &#39;.join([token.lemma_ for token in doc if not token.is_punct and not token.is_stop])<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)  # all generated<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br># daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br>del daigt, mistral, mine<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: DataFrame(s) with word2vec representation of shape (n_samples, 300) along with &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    df[&#39;word2vec_doc&#39;] = df[&#39;processed_text&#39;].apply(lambda text: nlp(text).vector)<br>    df.drop(&#39;processed_text&#39;, axis=1, inplace=True)<br>    <br>    if &#39;generated&#39; in df.columns.values:<br>        X_train, X_val, y_train, y_val = train_test_split(df[&#39;word2vec_doc&#39;], df[&#39;generated&#39;],<br>                                                  stratify=df[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br><br>        X_train = X_train.apply(pd.Series)<br>        X_val = X_val.apply(pd.Series)<br>        <br>        return X_train, X_val, y_train, <br><br>    # This is for X_test.<br>    return df[&#39;word2vec_doc&#39;].apply(pd.Series)<br><br>X_train, X_val, y_train, y_val = data_pipeline(all_data)<br><br>model = XGBClassifier(objective=&#39;binary:logistic&#39;)<br>model.fit(X_train, y_train, eval_metric=&quot;logloss&quot;, eval_set=[(X_val, y_val)], verbose=True)<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_data)<br>y_test_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_data.id, y_test_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mebT0oSzCn2doq23-8aFIA.png" /></figure><p>The score obtained was 0.781, a slight decrease in performance. This probably happened because the model was trained on additional essays with essay prompts different from the ones given in the hidden test set.</p><p>Afterward, I tried training BERT on the new data without the prompt_id feature with RDizzl3_seven values set to True. Preprocessing was done as before by removing punctuation and stop words, and by lemmatizing the remaining words.</p><pre>import spacy<br>import pandas as pd<br>import tensorflow as tf<br>import tensorflow_hub as hub<br>import tensorflow_text as text<br>from sklearn.model_selection import train_test_split<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, and lemmatizes the tokens.&#39;&#39;&#39;<br>    doc = nlp(text)   <br>    return &#39; &#39;.join([token.lemma_ for token in doc if not token.is_punct and not token.is_stop])<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)  # all generated<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: Series with processed text and &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    if &#39;generated&#39; in df.columns.values:<br>        X_train, X_val, y_train, y_val = train_test_split(df[&#39;processed_text&#39;], df[&#39;generated&#39;],<br>                                                  stratify=df[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br>        <br>        return X_train, X_val, y_train, y_val<br>    <br>    # This is for X_test.<br>    return df[&#39;processed_text&#39;]<br><br>preprocessor_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_preprocessor&quot;)<br>encoder_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_encoder&quot;)<br><br>X_train, X_val, y_train, y_val = data_pipeline(all_data)<br><br># Build the neural network<br>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=&#39;text_input&#39;)<br>encoder_inputs_bert = preprocessor_bert(text_input)<br>outputs_bert = encoder_bert(encoder_inputs_bert)<br><br>layer = tf.keras.layers.Dropout(0.2)(outputs_bert[&#39;pooled_output&#39;])<br>layer = tf.keras.layers.Dense(10, activation=&#39;relu&#39;)(layer)<br>layer = tf.keras.layers.Dropout(0.2)(layer)<br>layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(layer)  # sentence embedding<br><br>model = tf.keras.Model(inputs=[text_input], outputs=[layer])<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;,<br>    patience=5,<br>    restore_best_weights=True,<br>)<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[tf.keras.metrics.BinaryAccuracy(),<br>                       tf.keras.metrics.Precision(),<br>                       tf.keras.metrics.Recall()])<br><br>model.fit(X_train,<br>          y_train, epochs=30,<br>          validation_data=(X_val, y_val),<br>          callbacks=[early_stopping])<br><br>test_set = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_set)<br><br>y_pred = pd.Series(model.predict(X_test).flatten(), name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_set.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ALz2oeZNI1nOmqDtxKoeQ.png" /></figure><p>The obtained score was 0.739. For some reason, the word2vec with the XGBoost model performed better than the BERT model.</p><h3>Feature engineering and hyperparameter configurations</h3><p>So far, we have seen various ways in which we changed our model in hopes of increasing the score. We have feature-engineered two features and tested two hyperparameters:</p><ol><li>prompt_id feature — We could either include or exclude this feature along with the other data. After including it with the other data, we found that the score decreased, probably due to overfitting unnecessary information (noise) as this feature does not give any meaningful information whether an essay is human-written or AI-generated. As such, it is best to exclude it from our data.</li><li>RDizzl3_seven feature — This is a boolean value feature present in the DAIGT-V2 dataset that determines whether essays were written based on prompts included in the hidden test set of the competition. We could either include all of the samples or filter only the True samples. We have found that including only the True samples increases the score as we are training the model on data that is more representative of the data present in the hidden test set of the competition (by which we are evaluated).</li><li>text representation techniques — We have experimented with text representation techniques such as a bag of words, TF-IDF, and word2vec (and BERT’s encoder which was only used with BERT). We have found that word2vec is a convenient way to represent text data as it converts them into vectors of fixed length, preventing out-of-memory errors.</li><li>model — There are two main models that we have tried using in the competition: BERT and Gradient Boosting (XGBoost is a version of it). XGBoost turned out to have a higher performance than BERT. Yet another benefit of using XGBoost is that it trains for significantly less time compared to BERT.</li></ol><p>Now let’s discuss various other approaches to achieve a higher score.</p><h3>Using corrupted data</h3><p>Unlike LLM-generated essays, the essays written by students tend to contain spelling mistakes. This is a factor that needs to be considered as words that are misspelled could affect model training. A <a href="https://www.kaggle.com/competitions/llm-detect-ai-generated-text/discussion/458343">discussion</a> on Kaggle suggested that this factor can be dealt with in two ways: either correct the typos in the hidden test set or introduce typos into the training set. To that end, I obtained corrupted versions of <a href="https://www.kaggle.com/datasets/murugesann/llm-ai-detect-dataset-5/data">DAIGT-V2</a> and <a href="https://www.kaggle.com/datasets/carlmcbrideellis/llm-mistral-7b-instruct-texts">MISTRAL-7B</a> where typos were introduced to 15% of the human-written essays and LLM-generated essays, respectively. I have excluded my data from this part.</p><pre>import spacy<br>import pandas as pd<br>from xgboost import XGBClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import classification_report<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, and lemmatizes the tokens.&#39;&#39;&#39;<br>    doc = nlp(text)   <br>    return &#39; &#39;.join([token.lemma_ for token in doc if not token.is_punct and not token.is_stop])<br><br>daigt = pd.read_csv(&#39;/kaggle/input/corrupted-data/augmented-typos-introduced-ds5.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/corrupted-data/Mistral7B_CME_v7_15_percent_corruption.csv&#39;)  # all generated<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral], ignore_index=True)<br>del daigt, mistral<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: DataFrame(s) with word2vec representation of shape (n_samples, 300) along with &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    df[&#39;word2vec_doc&#39;] = df[&#39;processed_text&#39;].apply(lambda text: nlp(text).vector)<br>    df.drop(&#39;processed_text&#39;, axis=1, inplace=True)<br>        <br>    if &#39;generated&#39; in df.columns.values:<br>        X_train, X_val, y_train, y_val = train_test_split(df[&#39;word2vec_doc&#39;], df[&#39;generated&#39;],<br>                                                  stratify=df[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br><br>        X_train = X_train.apply(pd.Series)<br>        X_val = X_val.apply(pd.Series)<br>        <br>        return X_train, X_val, y_train, y_val<br>    <br>    # This is for X_test.<br>    return df[&#39;word2vec_doc&#39;].apply(pd.Series)<br><br>X_train, X_val, y_train, y_val = data_pipeline(all_data)<br><br>model = XGBClassifier(objective=&#39;binary:logistic&#39;)<br>model.fit(X_train, y_train, eval_metric=&quot;logloss&quot;, eval_set=[(X_val, y_val)], verbose=True)<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_data)<br>y_test_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_data.id, y_test_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fAq6mxQ3x65pxqMBYRbOg.png" /></figure><p>The obtained score was 0.782, a slight decrease from the best score. It might be a better idea to remove the spelling errors from both the training and hidden sets to ensure the data is clean from both sides. We will return to this later.</p><h3>Using Voting Classifier</h3><p>Scikit-learn has a class called VotingClassifier. It aggregates the predictions from multiple models to give one prediction. This could increase the performance as we can consider the prediction of multiple models instead of just one, producing more robust results. We can either choose ‘hard’ or ‘soft’ voting. The former indicates that the predicted class will be chosen based on the majority vote. For example, let’s say we included four models in our voting classifier, where 3 of the models voted for class 0 while one of them voted for class 1. In this case, the class 0 will be selected as the prediction. In contrast, soft voting takes the mean of the probabilities of all votes for a certain class. For example, let’s say the same four models predicted the following probabilities for class 0 [0.2, 0.3, 0.15, 0.8] and [0.8, 0.7, 0.85, 0.2] for class 1. The mean probability for class 0 is 0.3625 and for class 1 is 0.6375. Hence, class 1 will be selected as the prediction in this case. The following models were included in the voting classifier: LogisticRegression, LightGBM, XGBoost, CatBoost, KNN, RandomForest, and GradientBoosting. Additionally, all data from the original DAIGT-V2, MISTRAL-7B, and my own datasetswere used for training, i.e. validation set was not used.</p><pre>import spacy<br>import pandas as pd<br>import lightgbm as lgb<br>from xgboost import XGBClassifier<br>from catboost import CatBoostClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.ensemble import VotingClassifier, RandomForestClassifier, GradientBoostingClassifier<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, and lemmatizes the tokens.&#39;&#39;&#39;<br>    doc = nlp(text)   <br>    return &#39; &#39;.join([token.lemma_ for token in doc if not token.is_punct and not token.is_stop])<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br>del daigt, mistral, mine<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: Series with word2vec representation of shape (n_samples, 300) along with &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    df[&#39;word2vec_doc&#39;] = df[&#39;processed_text&#39;].apply(lambda text: nlp(text).vector)<br>    df.drop(&#39;processed_text&#39;, axis=1, inplace=True)<br>        <br>    if &#39;generated&#39; in df.columns.values:<br>        <br>        X = df[&#39;word2vec_doc&#39;].apply(pd.Series)<br>        y = df[&#39;generated&#39;]<br><br>        return X, y<br>    <br>    # This is for X_test.<br>    return df[&#39;word2vec_doc&#39;].apply(pd.Series)<br><br>X, y = data_pipeline(all_data)<br><br>estimators = [(&#39;lr&#39;, LogisticRegression()),<br>              (&#39;rf&#39;, RandomForestClassifier()),<br>              (&#39;knn&#39;, KNeighborsClassifier()),<br>              (&#39;gb&#39;, GradientBoostingClassifier()),<br>              (&#39;xgb&#39;, XGBClassifier(objective=&#39;binary:logistic&#39;)),<br>              (&#39;lgb&#39;, lgb.LGBMClassifier()),<br>              (&#39;cb&#39;, CatBoostClassifier(loss_function=&#39;Logloss&#39;))<br>             ]<br><br>model = VotingClassifier(estimators=estimators, voting=&#39;soft&#39;, verbose=True)<br><br>model.fit(X, y)<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_data)<br>y_test_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_data.id, y_test_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wAvAwrNOjbV0RWe8tUiCw.png" /></figure><p>These configurations produced a new best score of 0.794.</p><p>After that, out of curiosity, I resubmitted the previous notebook but by only including the gradient-boosting models in the voting classifier: LightGBM, XGBoost, CatBoost, and GradientBoosting (from scikit-learn).</p><pre>import spacy<br>import pandas as pd<br>import lightgbm as lgb<br>from xgboost import XGBClassifier<br>from catboost import CatBoostClassifier<br>from sklearn.ensemble import VotingClassifier, GradientBoostingClassifier<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, whitespaces, newlines, corrects typos, and lemmatizes the tokens.&#39;&#39;&#39;<br>    doc = nlp(text)<br>    filtered_tokens = [token.lemma_ for token in doc if not token.is_punct and not token.is_stop]<br>    return &#39; &#39;.join(filtered_tokens)<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br>del daigt, mistral, mine<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: Series with word2vec representation of shape (n_samples, 300) along with &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    df[&#39;word2vec_doc&#39;] = df[&#39;processed_text&#39;].apply(lambda text: nlp(text).vector)<br>    df.drop(&#39;processed_text&#39;, axis=1, inplace=True)<br>        <br>    if &#39;generated&#39; in df.columns.values:<br>        X = df[&#39;word2vec_doc&#39;].apply(pd.Series)<br>        y = df[&#39;generated&#39;]<br>        return X, y<br>    <br>    # This is for X_test.<br>    return df[&#39;word2vec_doc&#39;].apply(pd.Series)<br><br>X, y = data_pipeline(all_data)<br><br>estimators = [(&#39;gb&#39;, GradientBoostingClassifier()),<br>              (&#39;xgb&#39;, XGBClassifier(objective=&#39;binary:logistic&#39;)),<br>              (&#39;lgb&#39;, lgb.LGBMClassifier()),<br>              (&#39;cb&#39;, CatBoostClassifier(loss_function=&#39;Logloss&#39;))<br>             ]<br><br>model = VotingClassifier(estimators=estimators, voting=&#39;soft&#39;, verbose=True)<br><br>model.fit(X, y)<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_data)<br>y_test_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_data.id, y_test_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfG0fkNVgODRkepexg5V9A.png" /></figure><p>The score decreased to 0.777.</p><p>The voting classifier allows us to either choose soft or hard voting. As we have already used soft voting, it could be worth checking what results hard voting would give. However, an error message appeared that stated: AttributeError: predict_proba is not available when voting=’hard’. We are unable to view the probabilities of the class predictions when choosing hard voting. So I guess that’s where the hard voting option ends.</p><h3>Correcting spelling errors</h3><p>Now let’s consider correcting typos in both the training and hidden test sets. First, I tried using a T5-base model to correct the errors by following <a href="https://www.kaggle.com/code/meetnagadia/grammer-correction-using-t5-transformer">this post</a>. Due to submission errors, I had to manually upload the model as well as the jfleg dataset that was used to fine-tune it. After getting another error, I decided just to upload a jfleg-fine-tuned version of the T5-base model and use it without having to fine-tune it in the notebook. However, the notebook timed out after running for 12 hours with the following message: Your notebook was stopped because it exceeded the max allowed execution duration. Exit code: 137. Because of the slow run time, I switched to using the pyspellchecker package to correct typos instead. After fixing some formatting errors, it finally worked and I could submit my notebook.</p><pre>import re<br>import spacy<br>import pandas as pd<br>import lightgbm as lgb<br>from spellchecker import SpellChecker<br>from xgboost import XGBClassifier<br>from catboost import CatBoostClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.ensemble import VotingClassifier, RandomForestClassifier, GradientBoostingClassifier<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br>spell = SpellChecker()<br><br>def preprocess_text(text):<br>    &#39;&#39;&#39;Removes punctuation, stop words, whitespaces, newlines, corrects typos, and lemmatizes the tokens.&#39;&#39;&#39;<br><br>    text = re.sub(r&#39;[\n\r]+&#39;, &#39; &#39;, text)<br>    doc = nlp(text.strip())<br>    filtered_tokens = [token.lemma_.lower() for token in doc if not token.is_punct and not token.is_stop]<br>    misspelled = spell.unknown(filtered_tokens)<br><br>    for word in misspelled:<br>        corrected_word = spell.correction(word)  # problem was here<br>        if corrected_word != None:<br>            filtered_tokens[filtered_tokens.index(word)] = corrected_word<br>   <br>    return &#39; &#39;.join(filtered_tokens)<br><br>def data_pipeline(df):<br>    &#39;&#39;&#39;Input: DataFrame with `text` column and optional &#39;generated&#39; column.<br>       Output: Series with word2vec representation of shape (n_samples, 300) along with &#39;generated&#39; Series if present.&#39;&#39;&#39;<br>    <br>    df[&#39;processed_text&#39;] = df[&#39;text&#39;].map(preprocess_text)<br>    df.drop(&#39;text&#39;, axis=1, inplace=True)<br>    <br>    df[&#39;word2vec_doc&#39;] = df[&#39;processed_text&#39;].apply(lambda text: nlp(text).vector)<br>    df.drop(&#39;processed_text&#39;, axis=1, inplace=True)<br>        <br>    if &#39;generated&#39; in df.columns.values:<br>        X = df[&#39;word2vec_doc&#39;].apply(pd.Series)<br>        y = df[&#39;generated&#39;]<br>        return X, y<br>    <br>    # This is for X_test.<br>    return df[&#39;word2vec_doc&#39;].apply(pd.Series)<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br>daigt = daigt[daigt[&#39;RDizzl3_seven&#39;]==True]<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br>del daigt, mistral, mine<br><br>X, y = data_pipeline(all_data)<br><br>estimators = [(&#39;lr&#39;, LogisticRegression()),<br>              (&#39;rf&#39;, RandomForestClassifier()),<br>              (&#39;knn&#39;, KNeighborsClassifier()),<br>              (&#39;gb&#39;, GradientBoostingClassifier()),<br>              (&#39;xgb&#39;, XGBClassifier(objective=&#39;binary:logistic&#39;)),<br>              (&#39;lgb&#39;, lgb.LGBMClassifier()),<br>              (&#39;cb&#39;, CatBoostClassifier(loss_function=&#39;Logloss&#39;))<br>             ]<br><br>model = VotingClassifier(estimators=estimators, voting=&#39;soft&#39;, verbose=True)<br><br>model.fit(X, y)<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = data_pipeline(test_data)<br>y_test_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_data.id, y_test_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><p>The new score was 0.79, a slight decrease from the best score. I must note that this package sometimes changes words that do not need correction, such as names. This could change their meaning.</p><h3>Conclusion</h3><p>In conclusion, we experimented with a few more times with BERT. Next, we returned to using the gradient boosting model to find that it performed better and trained faster than BERT on the new data. We briefly summarized the different configurations used in our submissions as well as mentioned which of them were found to be optimal. Finally, we tried new approaches to solving the competition, namely by tackling the issue of typos and by including a voting classifier.</p><p>Thank you for reading this far. We have come a long way increasing the score from 0.511 to 0.794. Feel free to comment on your ideas, suggestions, and questions.</p><p>I am planning to make a simple web app with Streamlit based on this competition where it takes an essay as input and detects whether it is human-written or AI-generated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b2c2004eaf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 3)]]></title>
            <link>https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-3-95b418c595ff?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/95b418c595ff</guid>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 07:05:33 GMT</pubDate>
            <atom:updated>2024-01-10T14:38:09.892Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzLitE6u-0Ej9bY8wgbOAw.png" /></figure><p>In the previous post, we submitted our first notebook to the competition. However, we obtained a low score of 0.511. In this post, we will try to understand why that was the case and how we can improve it. If you wish to view the other posts, follow these links:</p><ul><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-1-c53b1b087795">Part 1</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-2-d9cc360d81ab">Part 2</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-4-0b2c2004eaf5">Part 4</a></li></ul><h4>Table of Contents</h4><p>· <a href="#b4f7">Understanding the scoring</a><br>· <a href="#f0c4">Improving the score</a><br>· <a href="#6f80">Including prompt_id feature</a><br>· <a href="#c1a9">Obtaining better data</a><br>· <a href="#8b80">Future Considerations</a></p><h3>Understanding the scoring</h3><p>The submitted notebook is run in the background against a hidden test set consisting of 9000 essays that have seven different prompts with both AI-generated and human-written essays. With this in mind, the data that we have trained our model does not fully represent the data that is present in the hidden test set. So to improve our score, we must provide additional, more representative data to the model. Other than that, using BERT as our model for text classification could improve the score even further as it uses a transformer. Finally, we can also try including the prompt_id feature to see if it affects the score in any way.</p><h3>Improving the score</h3><p>So first, let‘s use the BERT model on the data that we have. GPU P100 was used to speed up the training process. 30 epochs were used along with early stopping to prevent overfitting. Note that BERT has its own encoder that converts the text to numbers. The below notebook ran for almost 9 minutes.</p><pre>import pandas as pd<br>import tensorflow as tf<br>import tensorflow_hub as hub<br>import tensorflow_text as text<br><br>preprocessor_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_preprocessor&quot;)<br>encoder_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_encoder&quot;)<br><br>train_set = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/compiled_processed_train_data.csv&#39;)<br>val_set = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/compiled_processed_val_data.csv&#39;)<br><br>X_train = train_set[&#39;text&#39;]<br>X_val = val_set[&#39;text&#39;]<br>y_train = train_set.generated<br>y_val = val_set.generated<br><br># Build the neural network<br>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=&#39;text_input&#39;)<br>encoder_inputs_bert = preprocessor_bert(text_input)<br>outputs_bert = encoder_bert(encoder_inputs_bert)<br><br>layer = tf.keras.layers.Dropout(0.2)(outputs_bert[&#39;pooled_output&#39;])<br>layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(layer)  # sentence embedding<br><br>model = tf.keras.Model(inputs=[text_input], outputs=[layer])<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;,<br>    patience=5,<br>    restore_best_weights=True,<br>)<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[tf.keras.metrics.BinaryAccuracy(),<br>                       tf.keras.metrics.Precision(),<br>                       tf.keras.metrics.Recall()])<br><br>model.fit(X_train,<br>          y_train, epochs=30,<br>          validation_data=(X_val, y_val),<br>          callbacks=[early_stopping])<br><br>test_set = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = test_set[&#39;text&#39;]<br>y_pred = pd.Series(model.predict(X_test).flatten(), name=&#39;generated&#39;)#.round(1)<br><br>output_df = pd.concat((test_set.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3sNJ2omywKrVd8Aqfx_mw.png" /></figure><p>A new score of 0.708 was obtained. This is a significant improvement compared to word2vec and gradient boosting.</p><h3>Including prompt_id feature</h3><p>Now let’s try including the prompt_id feature in BERT as well. This notebook ran for over 9 minutes on GPU P100:</p><pre>import pandas as pd<br>import tensorflow as tf<br>import tensorflow_hub as hub<br>import tensorflow_text as text<br><br>preprocessor_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_preprocessor&quot;)<br>encoder_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_encoder&quot;)<br><br>train_set = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/compiled_processed_train_data.csv&#39;)<br>val_set = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/compiled_processed_val_data.csv&#39;)<br><br># needed for model inputting with prompt_id<br>X_train = {&#39;text&#39;: train_set[&#39;text&#39;], &#39;prompt_id&#39;: train_set[&#39;prompt_id&#39;]}<br>X_val = {&#39;text&#39;: val_set[&#39;text&#39;], &#39;prompt_id&#39;: val_set[&#39;prompt_id&#39;]}<br>y_train = train_set.generated<br>y_val = val_set.generated<br><br># Build the neural network<br>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=&#39;text&#39;)<br>encoder_inputs_bert = preprocessor_bert(text_input)<br>outputs_bert = encoder_bert(encoder_inputs_bert)<br><br>prompt_id_input = tf.keras.layers.Input(shape=(), dtype=tf.float32, name=&#39;prompt_id&#39;)<br>concatenated_input = tf.keras.layers.Concatenate()([outputs_bert[&#39;pooled_output&#39;],  # includes prompt_id<br>                                                     tf.expand_dims(prompt_id_input, axis=-1)])<br><br>layer = tf.keras.layers.Dropout(0.2)(concatenated_input)<br>layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(layer)<br><br>model = tf.keras.Model(inputs=[prompt_id_input, text_input], outputs=[layer])<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;,<br>    patience=5,<br>    restore_best_weights=True,<br>)<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[tf.keras.metrics.BinaryAccuracy(),<br>                       tf.keras.metrics.Precision(),<br>                       tf.keras.metrics.Recall()])<br><br>model.fit(X_train,<br>          y_train, epochs=30,<br>          validation_data=(X_val, y_val),<br>          callbacks=[early_stopping])<br><br>test_set = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = {&#39;text&#39;: test_set[&#39;text&#39;], &#39;prompt_id&#39;: test_set[&#39;prompt_id&#39;]}<br>y_pred = pd.Series(model.predict(X_test).flatten(), name=&#39;generated&#39;)#.round(1)<br><br>output_df = pd.concat((test_set.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mJHIIIfBaLTVG8a8mGmbg.png" /></figure><p>The newly obtained score was 0.699, a slight decrease when BERT was used without the prompt_id feature. This might have been due to small random fluctuations. Or it might have happened because only two out of seven prompt_id’s were given during training. This feature might be useful to consider when all seven prompt_ids are included in model training.</p><h3>Obtaining better data</h3><p>To further improve the score, we need to use data that better represents the samples in the hidden test set. Thanks to the Kaggle Community, we have access to such data compiled from different sources. We can use the <a href="https://www.kaggle.com/datasets/thedrcat/daigt-v2-train-dataset">DAIGT-V2</a> and <a href="https://www.kaggle.com/datasets/carlmcbrideellis/llm-mistral-7b-instruct-texts/data">MISTRAL-7B</a> datasets. Let’s explore both datasets with pandas to have an idea of what kind of data they contain, starting with the first one:</p><pre># Just a reminder that I ran this in Jupyter Notebook.<br><br>import pandas as pd<br><br>daigt = pd.read_csv(&#39;data/train_v2_drcat_02.csv&#39;)<br><br>daigt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mpjJuHjTgwu9Beb9LCAWA.png" /></figure><ol><li>text — Contains the contents of the essays.</li><li>label — Same as generated feature. 0 indicates human-written while 1 indicates AI-generated.</li><li>prompt_name — Same as prompt_id but stores the prompt name instead of numbers.</li><li>source — The source where the essays were obtained from.</li><li>RDizzl3_seven — Stores boolean (True/False) values. True indicates these samples belong to one of seven prompt_id values given by the competition organizers. False indicates that these essays do not belong to said values.</li></ol><p>The DAIGT-V2 dataset was compiled from other sources such as text generated by various LLMs. This allows for more diverse writing styles than if only one LLM (like ChatGPT-3.5) was used. Moreover, this dataset has 44868 essay samples, where 17497 are AI-generated and 27371 are human-written. It already contains the official train data from the competition, along with the data that was obtained from a Kaggle User (Radek). To that end, I only had to include the essays that I manually obtained from ChatGPT-3.5. It is worth mentioning that this dataset contains additional essays that have prompts different than the ones provided by the competition. Therefore, this increases the complexity of the data.</p><p>Now, let’s take a look at MISTRAL-7B:</p><pre>import pandas as pd<br><br>mistral = pd.read_csv(&#39;data/train_v2_drcat_02.csv&#39;)<br><br>mistral</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*bGzwG2uJD57QIbnJVbK_Qw.png" /></figure><ol><li>prompt_id — Contains the unique identifiers for prompts used to write the essays.</li><li>text — Same as before.</li><li>prompt_name — Contains the names of prompts used to write the essays.</li><li>generated — Same as before.</li></ol><p>This dataset consists of 4900 AI-generated essays. So if we collect all the data, we have 27,371 human-written and 22,497 LLM-generated essays. This is a substantial increase in the quality and quantity of data compared to the one which we were using. If we input this in BERT, we can expect an increase in model performance:</p><pre>import pandas as pd<br>import tensorflow as tf<br>import tensorflow_hub as hub<br>import tensorflow_text as text<br>from sklearn.model_selection import train_test_split<br><br>daigt = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_v2_drcat_02.csv&#39;)  # contains student written essays<br>mistral = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/Mistral7B_CME_v7.csv&#39;)  # all generated<br>mine = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/train_essays_chatgpt_manual.csv&#39;)  # all generated<br><br>daigt.rename(columns={&#39;label&#39;: &#39;generated&#39;}, inplace=True)<br><br>for df in (daigt, mistral, mine):<br>    df.drop(df.columns.difference([&#39;text&#39;, &#39;generated&#39;]), axis=1, inplace=True)<br><br>all_data = pd.concat([daigt, mistral, mine], ignore_index=True)<br><br>X_train, X_val, y_train, y_val = train_test_split(all_data[&#39;text&#39;], all_data[&#39;generated&#39;],<br>                                                  stratify=all_data[&#39;generated&#39;],<br>                                                  random_state=10, test_size=0.2)<br><br>preprocessor_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_preprocessor&quot;)<br>encoder_bert = hub.KerasLayer(&quot;/kaggle/input/bert-model-extracted/bert_encoder&quot;)<br><br># Build the neural network<br>text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name=&#39;text_input&#39;)<br>encoder_inputs_bert = preprocessor_bert(text_input)<br>outputs_bert = encoder_bert(encoder_inputs_bert)<br><br>layer = tf.keras.layers.Dropout(0.2)(outputs_bert[&#39;pooled_output&#39;])<br>layer = tf.keras.layers.Dense(10, activation=&#39;relu&#39;)(layer)<br>layer = tf.keras.layers.Dropout(0.2)(layer)<br>layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)(layer)  # sentence embedding<br><br>model = tf.keras.Model(inputs=[text_input], outputs=[layer])<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    monitor=&#39;val_loss&#39;,<br>    patience=5,<br>    restore_best_weights=True,<br>)<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[tf.keras.metrics.BinaryAccuracy(),<br>                       tf.keras.metrics.Precision(),<br>                       tf.keras.metrics.Recall()])<br><br>model.fit(X_train,<br>          y_train, epochs=50,<br>          validation_data=(X_val, y_val),<br>          callbacks=[early_stopping])<br><br>test_set = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = test_set[&#39;text&#39;]<br>y_pred = pd.Series(model.predict(X_test).flatten(), name=&#39;generated&#39;)<br><br>output_df = pd.concat((test_set.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><p>NOTE: This notebook ran for a whopping 2 hours and 56 minutes when GPU P100 was used, so expect to wait for some time if you decide to run it as well. You have been warned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fNugvs5VrnuMSVE3W96Xg.png" /></figure><p>In this instance, I combined DAIGT-V2, MISTRAL-7B, and my data into one before splitting the data and training the model. Furthermore, I set the training for 50 epochs just in case, as the volume of data was significantly larger. The new score was 0.731, a slight improvement over the last best one (I was hoping the score would be at least 0.900).</p><h3>Future Considerations</h3><p>In my opinion, the score can be improved if we feature engineer the data such that it will be more representative of the data contained in the hidden test set. We might see a change in performance if we exclude the essays that have prompts different from the ones given in the competition.</p><p>All in all, we gained some insight as to why the score was low. We replaced the gradient boosting model with BERT to significantly increase the score. We experimented with the prompt_id feature. Lastly, more, better data was obtained from the Kaggle Community that improved the score to some extent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95b418c595ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 2)]]></title>
            <link>https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-2-d9cc360d81ab?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9cc360d81ab</guid>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 08:07:46 GMT</pubDate>
            <atom:updated>2024-01-10T14:38:25.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaVvsSfkBvuBH3h3IsTjLg.png" /></figure><p>In the last post, we stopped at data preparation. In this post, I want to talk about how the essay text was converted into numbers, how a few models were trained on said numeric data, and how the first notebook was submitted. If you wish to view the other posts, follow these links:</p><ul><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-1-c53b1b087795">Part 1</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-3-95b418c595ff">Part 3</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-4-0b2c2004eaf5">Part 4</a></li></ul><h4>Table of Contents</h4><p>· <a href="#5075">Converting text to numbers</a><br>· <a href="#5fca">Choosing a model</a><br>· <a href="#63ac">First Submission</a></p><h3>Converting text to numbers</h3><p>Since ML models only take numbers as input, we need to somehow convert the text from the essays into a numeric format. This is called text representation. There are multiple ways of doing it. The ones I have chosen to try out are the following:</p><ol><li>bag of words (unigram) — Each unique word is saved in a vocabulary. A vector is made for each essay sample that contains the number of occurrences of the words in the vocabulary.</li><li>unigram with bigram — Works the same as a bag of words. However, unique pairs of words are included as well.</li><li>TF-IDF — Each unique word is saved in a vocabulary as before. TF (term frequency) and IDF (Inverse Document Frequency) scores are calculated for each word and multiplied to form a vector of numbers, one for each essay sample. This transformation causes words that occur multiple times in a single essay and rarely in other essays will have higher values in the vector.</li><li>word2vec — Unique words are saved in a vocabulary. Each word has a vector of fixed length (in our case 300). The numbers in the vector correspond to certain features. Some words have higher values for certain features while others do not. This causes words with similar meanings to have similar vectors.</li></ol><p>I did not explain everything in detail here, just a brief introduction to explain what’s going on. The code below converts the essay into numbers:</p><pre># This code takes some time to run.<br><br>import pandas as pd<br>import spacy<br>from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer<br><br>train_data = pd.read_csv(&#39;data/compiled_processed_train_data.csv&#39;)<br>val_data = pd.read_csv(&#39;data/compiled_processed_val_data.csv&#39;)<br><br>nlp = spacy.load(&#39;en_core_web_md&#39;)<br><br>bow_vectorizer = CountVectorizer()<br>uni_bi_gram_vectorizer = CountVectorizer(ngram_range=(1, 2))<br>tfidf_vectorizer = TfidfVectorizer()<br><br># initializing text representation features<br>for rep, vectorizer in zip([&#39;bow&#39;, &#39;uni_bi_gram&#39;, &#39;tfidf&#39;], [bow_vectorizer, uni_bi_gram_vectorizer, tfidf_vectorizer]):<br>    train_data[rep] = vectorizer.fit_transform(train_data[&#39;processed_text&#39;]).toarray().tolist()<br>    val_data[rep] = vectorizer.transform(val_data[&#39;processed_text&#39;]).toarray().tolist()<br><br>for data in (train_data, val_data):<br>    data[&#39;word2vec_doc&#39;] = data[&#39;text&#39;].apply(lambda text: nlp(text).vector)</pre><p>I applied the first three text representations to the previously saved processed_text column that contained the lemmatized form of the words without punctuation. However, I decided to use the original text when representing with word2vec. New columns were made to store the vectors of the above text representations: bow, uni_bi_gram, tfidf, and word2vec_doc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*vP7SR8JKnioVLUfa.png" /></figure><p>Here is the new DataFrame obtained. Each row in bow and tfidf columns stores a list containing 13185 elements. This indicates that there are 13185 unique words found in the train set (this DataFrame refers to the train set). Each row in uni_bi_gram column stores a list containing 166248 elements. As expected, this column has more elements as it includes unique pairs of words along with unique words. Each row in word2vec_doc column stores a NumPy array with a shape of (300,).</p><h3>Choosing a model</h3><p>At this point, we have four new columns containing various text representations of the essays. Now, let’s choose a few ML models so we can compare them to each other. The idea is to compare each text representation with each model to see which combination of them achieves the highest performance. We can use the F1 score as our metric to determine the performance. Logistic Regression, Random Forest, and Gradient Boosting models were chosen. We can use the scikit-learn library to import these models. The code below inputs the four text representations to the three models and then outputs the F1 score (along with other metrics) for each combination. The prompt_id feature was fed into the models as well.</p><pre># This code takes even more time to run.<br><br>from sklearn.metrics import classification_report<br>from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier<br>from sklearn.linear_model import LogisticRegression<br><br>model_logistic = LogisticRegression()<br>model_rf = RandomForestClassifier()<br>model_gb = GradientBoostingClassifier()<br><br>y_train = train_data.generated<br>y_val = val_data.generated<br><br>for model in (model_logistic, model_rf, model_gb):<br>    for rep in (&#39;bow&#39;, &#39;uni_bi_gram&#39;, &#39;tfidf&#39;, &#39;word2vec_doc&#39;):<br>        # flattening text representation column from lists into separate columns<br>        X_train = pd.concat([train_data[&#39;prompt_id&#39;], train_data[rep].apply(lambda x: pd.Series(x))], axis=1)<br>        X_train.columns = X_train.columns.astype(str)<br>        X_val = pd.concat([val_data[&#39;prompt_id&#39;], val_data[rep].apply(lambda x: pd.Series(x))], axis=1)<br>        X_val.columns = X_val.columns.astype(str)<br>        <br>        model.fit(X_train, y_train)<br>        <br>        y_pred = model.predict(X_val)<br>        print(f&#39;Model - {model} | Representation - {rep}&#39;)<br>        print(classification_report(y_val, y_pred))</pre><p>After the models’ training and validation were completed, the F1 scores for the 12 combinations were recorded. Almost all of them had either an F1 score of 0.99 or 1.00. These models would, most likely, not do so well in the actual competition to due various factors, however. Eventually, I just decided to go with the word2vec representation and the gradient boosting model.</p><h3>First Submission</h3><p>This Kaggle competition is a code competition. This means that we will have to submit a notebook that will then be run in the background for evaluation. We can upload additional files to the notebook to be used internally. Nevertheless, the internet connection to the notebook must be turned off to be able to submit (there is an option in the notebook for that). Below is the entire code used to submit to the competition. The prompt_id feature was not included in this submission. Note that I uploaded the following files to the notebook so that it would function properly: spaCy’s en_core_web_md model, compiled_processed_train_data.csv, and compiled_processed_val_data.csv. An output file should be made and named submission.csv.</p><pre># This is the code used to submit to the competition.<br><br>import spacy<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.metrics import classification_report<br><br>nlp = spacy.load(&#39;/kaggle/input/models/en_core_web_md_model&#39;)<br><br>def word2vec_data_pipeline(raw_train_data, raw_val_data):<br>    &#39;&#39;&#39;Inputs train and validation sets as DataFrames and outputs word2vec represented dataframes.&#39;&#39;&#39;<br>    <br>    for data in (raw_train_data, raw_val_data):<br>        data[&#39;word2vec_doc&#39;] = data[&#39;text&#39;].apply(lambda text: nlp(text).vector)<br>    <br>    X_train = raw_train_data[&#39;word2vec_doc&#39;].apply(pd.Series)<br>    X_val = raw_val_data[&#39;word2vec_doc&#39;].apply(pd.Series)<br>    X_train.columns = X_train.columns.astype(str)<br>    X_val.columns = X_val.columns.astype(str)<br><br>    y_train = raw_train_data.generated<br>    y_val = raw_val_data.generated<br><br>    return X_train, X_val, y_train, y_val<br><br>def word2vec_test_data_pipeline(raw_test_data):<br>    &#39;&#39;&#39;Inputs test dataset as a DataFrame and returns X_test as word2vec representation.&#39;&#39;&#39;<br>    <br>    raw_test_data[&#39;word2vec_doc&#39;] = raw_test_data[&#39;text&#39;].apply(lambda text: nlp(text).vector)  # the problem occurs here<br>    X_test = raw_test_data[&#39;word2vec_doc&#39;].apply(pd.Series)<br>    X_test.columns = X_test.columns.astype(str)<br><br>    return X_test<br><br>train_data = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/compiled_processed_train_data.csv&#39;)<br>val_data = pd.read_csv(&#39;/kaggle/input/kaggle-llm-competition-collected-data/compiled_processed_val_data.csv&#39;)<br>X_train, X_val, y_train, y_val = word2vec_data_pipeline(train_data, val_data)<br><br>model = GradientBoostingClassifier()<br>model.fit(X_train, y_train)<br>y_val_pred = model.predict(X_val)<br>print(classification_report(y_val, y_val_pred))<br><br>test_data = pd.read_csv(&#39;/kaggle/input/llm-detect-ai-generated-text/test_essays.csv&#39;)<br>X_test = word2vec_test_data_pipeline(test_data)<br>y_pred = pd.Series(model.predict_proba(X_test)[:, 1], name=&#39;generated&#39;).round(1)<br><br>output_df = pd.concat((test_data.id, y_pred), axis=1)<br>output_df.to_csv(&#39;submission.csv&#39;, index=False)</pre><p>NOTE: In reality, I had to submit the notebook several times before I got the submission formatting right. The competition only allows five submissions per day. So I had to wait the next day after failing to submit four times and succeeding once:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*G-NffY9b4A9ameA2.png" /></figure><p>The submission score was 0.511, which is pretty low. I have a few theories as to why we are getting this score. But that is a discussion for another post.</p><p>To recap, we converted the text into numbers through various text representation methods, trained the numeric data on three models, chose word2vec representation and gradient boosting model for the submission, and finally, submitted the first notebook.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9cc360d81ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 1)]]></title>
            <link>https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-1-c53b1b087795?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53b1b087795</guid>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 10:17:27 GMT</pubDate>
            <atom:updated>2024-01-10T14:38:40.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trying to solve a Kaggle Competition: LLM — Detect AI Generated Text (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgQkPn1JHhZ2CwCrDtwJUA.png" /></figure><p>In the next few blog posts, I want to talk about my journey on how I tried to solve a Kaggle Competition called ‘LLM — Detect AI Generated Text’. <a href="https://www.kaggle.com/competitions/llm-detect-ai-generated-text">Here is the link</a> for reference. If you wish to skip to the other posts, use these links:</p><ul><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-2-d9cc360d81ab">Part 2</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-3-95b418c595ff">Part 3</a></li><li><a href="https://medium.com/@odil.tokhirov/trying-to-solve-a-kaggle-competition-llm-detect-ai-generated-text-part-4-0b2c2004eaf5">Part 4</a></li></ul><h4>Table of Contents:</h4><p>· <a href="#9dbd">Introduction to the competition</a><br>· <a href="#97e2">Obtaining Additional Data</a><br>· <a href="#8910">Preparing the data</a></p><h3>Introduction to the competition</h3><p>The objective of this competition is to develop machine learning models that can detect whether an essay is authored by a human or generated by an LLM. The organizers have already provided us with some starting data stored in train_essays.csv file. So let’s load the data using pandas to get a better understanding of its structure. I used a Jupyter Notebook to run the code since it lets me view the results in a rich format. Additionally, it allows me to divide the code into separate cells and run only specific portions of the code so I don’t have to rerun the entire notebook.</p><pre># The `train_essays.csv` file is stored in the `data` folder.<br><br>import pandas as pd<br><br>df = pd.read_csv(&#39;data/train_essays.csv&#39;)<br><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*6PDXK_m-5O9sQJcPBmx-sQ.png" /></figure><p>The train_essays.csv file contains four columns. Each row corresponds to one essay entry. The id column stores unique identifier values for each essay. The prompt_id column stores positive integers that refer to the different instructions (prompts) given to students to write the essays. For example, prompt_id of 0 has a prompt name Car-free cities with the following instructions:</p><p>Write an explanatory essay to inform fellow citizens about the advantages of limiting car usage. Your essay must be based on ideas and information that can be found in the passage set. Manage your time carefully so that you can read the passages; plan your response; write your response; and revise and edit your response. Be sure to use evidence from multiple sources; and avoid overly relying on one source. Your response should be in the form of a multiparagraph essay. Write your essay in the space provided.</p><p>There are a total of seven different prompt_id values that are given in the hidden test set of the competition. However, the train set that we are provided with only contains two out of seven of these prompt types. The text column contains the contents of the essay. Finally, the generated column can contain only two values: either 0 or 1. The former refers to essays written by a human and the latter refers to those generated by an AI. Our machine-learning model must use the text column along with any other necessary features to predict the value of thegenerated column.</p><p>To gain more insight on the data, we can run the following code to view the class distributions:</p><pre>df.generated.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*MlUrwnuLyFbRcaFefVlgIA.png" /></figure><p>There are 1375 student-written essays and 3 AI-generated. The large difference in class distributions could skew an ML model to predict that a given essay is written by a human even if it&#39;s AI-generated. The competition rules allow us to use additional generated data from LLMs. Therefore, that is our next objective.</p><h3>Obtaining Additional Data</h3><p>A good first approach to generate more data would be to prompt ChatGPT-3.5. OpenAI has an API for ChatGPT-3.5 that allows users to obtain the results on a large scale. After exploring their documentation, I realized that I had to pay to use their API. For that reason, I decided to gather the generated data manually instead. I gave it the prompt instructions and obtained 100 essays by copy-pasting them on .txt files, one file per essay. I distributed 50 essays for each of the two prompt_id values. Sometimes, extra new lines would appear at the start and the end of the files after pasting the essay contents. Hence, I used the following script to remove those new lines to avoid any potential future issues:</p><pre># `chatgpt_manual_car` and `chatgpt_manual_car` folders are stored in `data` folder.<br># Each of them contains 50 .txt files with numbers from 1-50 as their names.<br><br>for prompt_type in (&#39;car&#39;, &#39;college&#39;):<br>    for i in range(1, 51):<br>        with open(f&#39;data/chatgpt_manual_{prompt_type}/{i}.txt&#39;, &#39;r&#39;) as file:<br>            content = file.read().strip(&#39;\n&#39;)<br><br>        with open(f&#39;data/chatgpt_manual_{prompt_type}/{i}.txt&#39;, &#39;w&#39;) as file:<br>            file.write(content)</pre><p>Next, I combined the 100 .txt files into one .csv file using the following code:</p><pre>import pandas as pd<br>import os<br><br>df = pd.DataFrame(columns=[&#39;prompt_id&#39;, &#39;text&#39;, &#39;generated&#39;])<br><br>for essay_topic in (&#39;car&#39;, &#39;college&#39;):<br>    essay_topic_to_prompt_id = {&#39;car&#39;: 0,<br>                                &#39;college&#39;: 1}<br><br>    directory_path = f&#39;data/chatgpt_manual_{essay_topic}&#39;<br><br>    for filename in os.listdir(directory_path):<br>        if filename.endswith(&#39;.txt&#39;):<br>            file_path = os.path.join(directory_path, filename)<br><br>            with open(file_path, &#39;r&#39;) as file:<br>                text_content = file.read()<br><br>            df = df._append({&#39;prompt_id&#39;: essay_topic_to_prompt_id[essay_topic],<br>                        &#39;text&#39;: text_content, &#39;generated&#39;: 1}, ignore_index=True)<br><br>csv_file_path = f&#39;data/train_essays_chatgpt_manual.csv&#39;<br>df.to_csv(csv_file_path, index=False)</pre><p>An additional 700 generated essays were obtained from a Kaggle User (Radek). They were generated using GPT-3.5 and GPT-4. <a href="https://www.kaggle.com/datasets/radek1/llm-generated-essays">Here is the link</a> to the data provided.</p><p>While not completely balanced yet, data consisting of 1375 human-written and 803 AI-generated essays was a good place to start training an ML model.</p><h3>Preparing the data</h3><p>At this point, we have four .csv files that contain the data we need. The first is the train_essays.csv file given to us by the competition organizers. The second is the train_essays_chatgpt_manual.csv file that contains the manually generated essays from ChatGPT-3.5. Finally, the last two are train_essays_gpt-3.5-turbo_automatic.csv and train_essays_gpt-4_automatic.csv, which were given by the Kaggle User (I renamed them from their original names).</p><p>We need to combine all of them into one file. The important features that must be included are prompt_id, text, and generated. In addition to those features, I decided to add a new column processed_text that will contain the essay’s text without punctuation in a lemmatized form (the base form of a word). We will need this processed text later. Lastly, we need to split and save the data into train and validation sets. The code below helps us achieve the above goals:</p><pre># spaCy allows us to remove punctuations and perform lemmatization of tokens (words and punctuations marks).<br><br>import spacy<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br><br>nlp = spacy.load(&#39;en_core_web_md&#39;)<br><br>def preprocess(text):<br>    &#39;&#39;&#39;Removes punctuation from a given text and performs lemmatization.&#39;&#39;&#39;<br>    doc = nlp(text)<br>    selected_tokens = [token.lemma_ for token in doc if not token.is_punct]<br>    return &#39; &#39;.join(selected_tokens)<br><br>data1 = pd.read_csv(&#39;data/train_essays.csv&#39;)<br>data2 = pd.read_csv(&#39;data/train_essays_chatgpt_manual.csv&#39;)<br>data3 = pd.read_csv(&#39;data/train_essays_gpt-3.5-turbo_automatic.csv&#39;)<br>data4 = pd.read_csv(&#39;data/train_essays_gpt-4_automatic.csv&#39;)<br><br>data = pd.concat([data1, data2, data3, data4], ignore_index=True).drop(&#39;id&#39;, axis=1)<br><br>data[&#39;processed_text&#39;] = data.text.apply(preprocess)<br><br># `stratify` parameter of `generated` feature allows us to have similar<br># distrubution of 0 and 1 values in training and validation sets<br>train_data, val_data = train_test_split(data, stratify=data.generated, <br>                                         random_state=10, test_size=0.2<br>                                        )<br><br>train_data.to_csv(&#39;data/compiled_processed_train_data.csv&#39;)<br>val_data.to_csv(&#39;data/compiled_processed_val_data.csv&#39;)</pre><p>The prepared train and validation data are stored in compiled_processed_train_data.csv and compiled_processed_val_data.csv files, respectively.</p><p>In this post, we have been briefly introduced to the competition, seen how the data is structured, obtained additional AI-generated data, and prepared the data so we can later use them in ML models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53b1b087795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Hand Gesture Recognition Model in Python — Part 2]]></title>
            <link>https://medium.com/@odil.tokhirov/how-i-built-a-hand-gesture-recognition-model-in-python-part-2-5d8987bb0756?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d8987bb0756</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[hand-gesture-recognition]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 06:19:18 GMT</pubDate>
            <atom:updated>2023-10-03T06:59:03.606Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Built a Hand Gesture Recognition Model in Python — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JICXrgq29m80jJNlpA6d7w.jpeg" /><figcaption><a href="https://www.freepik.com/free-photo/close-up-interpreter-teaching-sign-language_8969180.htm#from_view=detail_alsolike">Image by</a> Freepik</figcaption></figure><p>Click <a href="https://medium.com/@odil.tokhirov/how-i-built-a-hand-gesture-recognition-model-in-python-part-1-db378cf196e6">here</a> if you did not read part 1.</p><h3>Rebuilding the Model</h3><p>Last time, we left off where I could not achieve proper predictions on my model. I was thinking of applying image segmentation to the hand. Eventually, I decided to use only one image as input to the model instead of a sequence of images. This simplifies the problem, but I won’t be able to use hand motion anymore and will have to perform gestures while keeping my hand in a single position. Additionally, instead of using image segmentation, I returned to using Mediapipe to detect the hand landmarks. So my data now was in the form of an array that contained the position of landmarks instead of using the whole image. This is much cleaner than using whole images since I am not including unnecessary information. As I was not using the images themselves as the input, data augmentation was not needed. Since hand motions could not be used anymore, ‘zero’, ‘three’, ‘closed’, and ‘open’ hand gestures were used (refer to <a href="https://github.com/odil-T/Hand-Gesture-Recognition/tree/main">GitHub</a> to see what they look like). Here is the code that helped me save the landmark positions:</p><pre># hand_landmark_dataset_maker.py<br># program that saves the landmarks of the hand in a numpy array along with their images<br># press R to start saving, Q to exit the program<br><br>import mediapipe as mp<br>import cv2<br>import numpy as np<br>import os<br><br>subdir = &#39;hand_zero&#39;               # specify class subdirectory<br>n_samples_save = 100                # specify how many samples per category to save<br>mp_drawing = mp.solutions.drawing_utils<br>mp_hands = mp.solutions.hands<br>iteration_counter = n_samples_save + 1<br>folder_counter = 1<br>X, y = [], []<br>mapping = {<br>    &#39;hand_closed&#39;: 0,<br>    &#39;hand_three&#39;: 1,<br>    &#39;hand_open&#39;: 2,<br>    &#39;hand_zero&#39;: 3,<br>}<br><br>hands = mp_hands.Hands(min_detection_confidence=0.2, static_image_mode=True)<br>capture = cv2.VideoCapture(0)  # 0 integrated | 1 plugged<br>while capture.isOpened():<br>    ret, frame = capture.read()<br>    frame = cv2.flip(frame, 1)<br>    image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>    detected_image = hands.process(image)<br>    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)<br>    one_sample = []<br><br>    if detected_image.multi_hand_landmarks:<br>        for hand_lms in detected_image.multi_hand_landmarks:<br>            mp_drawing.draw_landmarks(image, hand_lms,<br>                                      mp_hands.HAND_CONNECTIONS,<br>                                      landmark_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                          color=(255, 0, 255), thickness=4, circle_radius=2),<br>                                      connection_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                          color=(20, 180, 90), thickness=2, circle_radius=2)<br>                                      )<br><br>    cv2.imshow(&#39;Dataset Maker&#39;, image)<br><br>    if cv2.waitKey(1) &amp; 0xFF == ord(&#39;r&#39;):<br>        iteration_counter = 1<br><br>    if iteration_counter &lt; n_samples_save + 1:<br>        cv2.imwrite(os.path.join(&#39;data&#39;, subdir, f&#39;{subdir}_image{iteration_counter}.jpg&#39;), image)<br>        if detected_image.multi_hand_landmarks:<br>            for hand_lms in detected_image.multi_hand_landmarks:<br>                for lm in hand_lms.landmark:<br>                    one_sample.extend([lm.x, lm.y])<br>                X.append(one_sample)<br>                y.append(mapping[subdir])<br>        if iteration_counter == n_samples_save:<br>            print(f&#39;Images for category {subdir} saved.&#39;)<br>        iteration_counter += 1<br><br>    if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>        break<br><br>capture.release()<br>cv2.destroyAllWindows()<br><br>X = np.array(X)<br>y = np.array(y)<br>print(X.shape)<br>print(y.shape)<br><br>np.savez(os.path.join(&#39;data&#39;, f&#39;data_{subdir}.npz&#39;), X=X, y=y)</pre><p>A neural network, XGBoost, and random forest algorithms were used to train the model on the data to determine which produced the best results. First, the XGBoost model was trained and tested but produced poor results. To try to fix the issue, better room lighting was provided so that Mediapipe could properly recognize the hand edges and the BGR image captured by OpenCV was converted to RGB which Mediapipe used (I previously removed it). Nevertheless, neither solution helped fix the problem. So perhaps the problem was in the model itself. Here is the code that was used to train the XGBoost model:</p><pre># model_hand_xgb.py<br># loads the saved data and trains the XGBoost model for single image classification<br><br>import pandas as pd<br>import xgboost as xgb<br>import numpy as np<br>import tensorflow as tf<br>import datetime as dt<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split, GridSearchCV<br>from sklearn.metrics import accuracy_score<br>import joblib<br><br># loading data<br>class_names = [&#39;hand_closed&#39;, &#39;hand_three&#39;, &#39;hand_open&#39;, &#39;hand_four&#39;]<br>loaded_data = np.load(fr&#39;data\data_{class_names[0]}.npz&#39;)<br>X, y = loaded_data[&#39;X&#39;], loaded_data[&#39;y&#39;]<br>for data_class in class_names[1:]:<br>    loaded_data = np.load(fr&#39;data\data_{data_class}.npz&#39;)<br>    X = np.vstack((X, loaded_data[&#39;X&#39;]))<br>    y = np.concatenate((y, loaded_data[&#39;y&#39;]))<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, test_size=0.2, random_state=1, stratify=y)<br># X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, shuffle=True, test_size=0.25, random_state=1, stratify=y_train)<br><br>with tf.device(&#39;/GPU:0&#39;):<br>    model = xgb.XGBClassifier()<br>    model.fit(X_train, y_train)<br>    yhat_test = model.predict(X_test)<br>    test_accuracy = accuracy_score(y_test, yhat_test)<br>    print(f&#39;Accuracy: {test_accuracy}&#39;)<br><br>    date_time_format = &#39;%Y_%m_%d__%H_%M_%S&#39;<br>    current_date_time_dt = dt.datetime.now()<br>    current_date_time_str = dt.datetime.strftime(current_date_time_dt, date_time_format)<br><br>    model_name = f&#39;model_xgb__date_time_{current_date_time_str}__acc_{test_accuracy}__hand__oneimage.pkl&#39;<br>    joblib.dump(model, model_name)</pre><p>Later, I trained and tested the random forest model. Surprisingly, this model predicted correctly most of the time. It did predict incorrectly when my hand was positioned farther from the webcam. Other than that, the results of this model were satisfactory. I must note that I had other types of gestures different from the four that I am using right now. I replaced them because they were too similar to each other and the model kept confusing them. This process took place when testing the random forest model. Here is the code that was used to train the Random Forest model:</p><pre># model_hand_rf.py<br># loads the saved data and trains the Random Forest model for single image classification<br><br>from sklearn.ensemble import RandomForestClassifier<br>import numpy as np<br>import tensorflow as tf<br>import datetime as dt<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br>import joblib<br><br># loading data<br>class_names = [&#39;hand_closed&#39;, &#39;hand_three&#39;, &#39;hand_open&#39;, &#39;hand_zero&#39;]<br>loaded_data = np.load(fr&#39;data\data_{class_names[0]}.npz&#39;)<br>X, y = loaded_data[&#39;X&#39;], loaded_data[&#39;y&#39;]<br>for data_class in class_names[1:]:<br>    loaded_data = np.load(fr&#39;data\data_{data_class}.npz&#39;)<br>    X = np.vstack((X, loaded_data[&#39;X&#39;]))<br>    y = np.concatenate((y, loaded_data[&#39;y&#39;]))<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, test_size=0.2, random_state=1, stratify=y)<br># X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, shuffle=True, test_size=0.25, random_state=1, stratify=y_train)<br>print(X_train.shape)<br># print(X_valid.shape)<br>print(X_test.shape)<br><br>with tf.device(&#39;/GPU:0&#39;):<br>    model = RandomForestClassifier()<br>    model.fit(X_train, y_train)<br><br>    yhat_test = model.predict(X_test)<br>    test_accuracy = accuracy_score(y_test, yhat_test)<br>    print(f&#39;Accuracy: {test_accuracy}&#39;)<br><br>    date_time_format = &#39;%Y_%m_%d__%H_%M_%S&#39;<br>    current_date_time_dt = dt.datetime.now()<br>    current_date_time_str = dt.datetime.strftime(current_date_time_dt, date_time_format)<br><br>    model_name = f&#39;model_rf__date_time_{current_date_time_str}__acc_{test_accuracy}__hand__oneimage.pkl&#39;<br>    joblib.dump(model, model_name)</pre><p>Finally, a dense neural network was trained and tested for comparison. It performed relatively well similar to the random forest model. The main problem was that the predictions were slightly slower compared to the random forest model. Other than that, it had a minor issue where the program would incorrectly predict ‘closed’ rather than ‘open’ when I slightly brought my fingers closer to each other in the ‘open’ state. Here is the code that was used to train the neural network model:</p><pre># model_hand_nn.py<br># loads the saved data and trains the Dense Neural Network model<br><br>import pandas as pd<br>import numpy as np<br>import tensorflow as tf<br>import datetime as dt<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from tensorflow.python.keras.layers import *<br>from tensorflow.keras.layers import *<br><br># loading data<br>class_names = [&#39;hand_closed&#39;, &#39;hand_three&#39;, &#39;hand_open&#39;, &#39;hand_zero&#39;]<br>loaded_data = np.load(fr&#39;data\data_{class_names[0]}.npz&#39;)<br>X, y = loaded_data[&#39;X&#39;], loaded_data[&#39;y&#39;]<br>for data_class in class_names[1:]:<br>    loaded_data = np.load(fr&#39;data\data_{data_class}.npz&#39;)<br>    X = np.vstack((X, loaded_data[&#39;X&#39;]))<br>    y = np.concatenate((y, loaded_data[&#39;y&#39;]))<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True, stratify=y)<br><br>early_stopping = tf.keras.callbacks.EarlyStopping(<br>    patience=10,<br>    restore_best_weights=True,<br>)<br><br>with tf.device(&#39;/GPU:0&#39;):<br>    model = tf.keras.Sequential([<br>        Dense(16, activation=&#39;relu&#39;, input_shape=(42,)),<br>        BatchNormalization(),<br>        Dropout(0.3),<br><br>        Dense(16, activation=&#39;relu&#39;),<br>        BatchNormalization(),<br>        Dropout(0.3),<br><br>        Dense(4),<br>    ])<br><br>    model.compile(<br>        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),<br>        optimizer=tf.keras.optimizers.Adam(),<br>        metrics=[&#39;accuracy&#39;],<br>    )<br><br>    model_train_hist = model.fit(<br>        X_train, y_train,<br>        shuffle=True,<br>        batch_size=50,<br>        epochs=70,<br>        validation_split=0.25,<br>        callbacks=[early_stopping],<br>    )<br>    print(model.summary())<br><br>    model_eval_loss, model_eval_acc = model.evaluate(X_test, y_test)<br>    date_time_format = &#39;%Y_%m_%d__%H_%M_%S&#39;<br>    current_date_time_dt = dt.datetime.now()<br>    current_date_time_str = dt.datetime.strftime(current_date_time_dt, date_time_format)<br><br>    model_name = f&#39;model_nn__date_time_{current_date_time_str}__loss_{model_eval_loss}__acc_{model_eval_acc}__hand__oneimage.h5&#39;<br>    model.save(model_name)<br><br>    df_train_hist = pd.DataFrame(model_train_hist.history)<br>    df_train_hist.loc[:, [&#39;loss&#39;, &#39;val_loss&#39;]].plot()<br>    plt.show()</pre><h3>Writing the Final Program</h3><p>After selecting the random forest model, it was time to implement the hand gesture recognition program. The program captures the images, detects the landmarks, feeds the data into the model, outputs the predictions of the model, and activates certain arrow keys depending on the gestures in real time. Here is its code:</p><pre># hand_gesture_reader.py<br># opens the webcam, predicts the gesture shown, activates arrow keys<br># press Q to close the webcam<br><br>import mediapipe as mp<br>import cv2<br>import numpy as np<br>import joblib<br>import pyautogui as pag<br><br>model_name_rf = &#39;model_rf__date_time_2023_09_23__12_22_48__acc_1.0__hand__oneimage.pkl&#39;<br>model_name_xgb = &#39;model_XGBoost__date_time_2023_09_23__11_55_17__acc_1.0__hand__oneimage.pkl&#39;<br>model_name_nn = &#39;&#39;<br>model = joblib.load(model_name_rf)<br>mp_drawing = mp.solutions.drawing_utils<br>mp_hands = mp.solutions.hands<br>idx_to_class = {<br>    0: &#39;Closed&#39;,<br>    1: &#39;Three&#39;,<br>    2: &#39;Open&#39;,<br>    3: &#39;Zero&#39;,<br>}<br>class_to_key = {<br>    &#39;Closed&#39;: &#39;up&#39;,<br>    &#39;Three&#39;: &#39;right&#39;,<br>    &#39;Open&#39;: &#39;left&#39;,<br>    &#39;Zero&#39;: &#39;down&#39;,<br>}<br><br>current_command = None<br><br>hands = mp_hands.Hands(static_image_mode=True, min_detection_confidence=0.4)<br>capture = cv2.VideoCapture(0)  # 0 integrated | 1 plugged<br>while capture.isOpened():<br>    ret, frame = capture.read()<br>    height, width = frame.shape[:-1]<br>    frame = cv2.flip(frame, 1)<br>    image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>    detected_image = hands.process(image)<br>    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)<br>    x = []<br><br>    if detected_image.multi_hand_landmarks:<br>        for hand_lms in detected_image.multi_hand_landmarks:<br>            mp_drawing.draw_landmarks(image, hand_lms,<br>                                      mp_hands.HAND_CONNECTIONS,<br>                                      landmark_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                          color=(255, 0, 255), thickness=4, circle_radius=2),<br>                                      connection_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                          color=(20, 180, 90), thickness=2, circle_radius=2)<br>                                      )<br>            for lm in hand_lms.landmark:<br>                x.extend([lm.x, lm.y])<br><br>        x = np.array(x)  # 1D array of current landmark positions<br>        x_max = int(width * np.max(x[::2]))<br>        x_min = int(width * np.min(x[::2]))<br>        y_max = int(height * np.max(x[1::2]))<br>        y_min = int(height * np.min(x[1::2]))<br>        x = x[None, :]  # adds a new dimension to x to avoid input shape error<br>        yhat_idx = int(model.predict(x)[0])<br>        yhat = idx_to_class[yhat_idx]<br>        print(yhat)<br><br>        cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (255, 0, 0), 3)  # draws a rectangle and types the predicted class<br>        cv2.putText(image, f&#39;{yhat}&#39;, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 0, 0), 2)<br><br>        if current_command != yhat:  # performs the new action once<br>            pag.press(class_to_key[yhat])<br>            current_command = yhat<br><br>    cv2.imshow(&#39;Hand Gesture Reader&#39;, image)<br>    if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>        break<br><br>capture.release()<br>cv2.destroyAllWindows()</pre><p>The pyautogui library was used to activate the arrow keys based on certain gesture predictions. The mapping is given in the class_to_key dictionary. As the while loop continuously outputs the prediction, the arrow keys would be activated multiple times. To prevent this, current_command variable was used to ensure that the arrow key would be activated only once depending on whether the new gesture is different from the previous one.</p><h3>Conclusion</h3><p>And so we have finally completed building the hand gesture recognition program. The benefit of doing such projects is that it can provide the experience to overcome project-specific problems. If you have suggestions or comments, then let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d8987bb0756" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Hand Gesture Recognition Model in Python — Part 1]]></title>
            <link>https://medium.com/@odil.tokhirov/how-i-built-a-hand-gesture-recognition-model-in-python-part-1-db378cf196e6?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/db378cf196e6</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[hand-gesture-recognition]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 06:07:06 GMT</pubDate>
            <atom:updated>2023-10-03T06:44:35.822Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Built a Hand Gesture Recognition Model in Python — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeuwaO1C5QlXXXdmSnZ4fQ.jpeg" /><figcaption><a href="https://www.freepik.com/free-photo/hand-gesture-pointing-invisible-screen_15669388.htm#query=hand%20gesture%20recognition&amp;position=2&amp;from_view=search&amp;track=ais">Image by rawpixel.com</a> on Freepik</figcaption></figure><p>Click <a href="https://medium.com/@odil.tokhirov/how-i-built-a-hand-gesture-recognition-model-in-python-part-2-5d8987bb0756">here</a> for part 2.</p><p>In this and the next blog, I want to document my journey on how I built a model that can recognize different hand gestures and perform certain commands with it. The source code of the program can be found in my <a href="https://github.com/odil-T/Hand-Gesture-Recognition">GitHub repository</a>.</p><p>A hand gesture recognition model is a program that detects the hand, figures out which gesture the hand is performing, and predicts that gesture. We may additionally decide to perform certain actions based on certain predictions. My original plan was to perform up, down, right and left hand motions that would be predicted as one gesture. In other words, the input would be an ordered sequence of images and the output would be a classification task.</p><h3>Getting Data</h3><p>So my first task was to somehow detect the hand. To do this, I decided to use a library called Mediapipe. Mediapipe can detect the position of the hand in the image along with the landmarks of the hand. The landmarks are different points on the hand (e.g. joints). I used OpenCV, a computer vision library, to open the webcam. Here is the code that helped me do this:</p><pre>import mediapipe as mp<br>import cv2<br><br>mp_drawing = mp.solutions.drawing_utils<br>mp_hands = mp.solutions.hands<br><br>capture = cv2.VideoCapture(0)<br><br>with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands:<br>  while capture.isOpened():<br>      ret, frame = capture.read()<br>      frame = cv2.flip(frame, 1)<br>      image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>      detected_image = hands.process(image)<br>      image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)<br>  <br>      if detected_image.multi_hand_landmarks:<br>          for hand_lms in detected_image.multi_hand_landmarks:<br>              mp_drawing.draw_landmarks(image, hand_lms,<br>                                        mp_hands.HAND_CONNECTIONS,<br>                                        landmark_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                            color=(255, 0, 255), thickness=4, circle_radius=2),<br>                                        connection_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                            color=(20, 180, 90), thickness=2, circle_radius=2)<br>                                        )<br>  <br>      cv2.imshow(&#39;Webcam&#39;, image)<br>  <br>      if cv2.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>          break<br><br>capture.release()<br>cv2.destroyAllWindows()</pre><p>When run, this code opens a webcam and draws the landmarks on the hand on the current frame. The code capture = cv2.VideoCapture(0) specifies to use the integrated webcam (0) for capture. One iteration of the while loop refers to one frame of the captured video. The line frame = cv2.flip(frame, 1) flips the image horizontally such that the program produces an image like a mirror. The line image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) converts the image from BGR to RGB colored because OpenCV uses the BGR color channels while Mediapipe uses RGB. To close the webcam, press ‘Q’. Here is an example of one frame that is produced with the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*it3Z55ccMkQ8t_Nbr0hDrw.jpeg" /></figure><p>For the model to understand which gesture the hand is performing, it would have to be trained first. This requires data. So my next step is to generate data which can then later be used to train and test my model. As I have stated before, I would need a series of images to be used as one input. So I made a folder called ‘data’ that stored subdirectories ‘hand_up’, ‘hand_down’, ‘hand_right’, and ‘hand_left’. These were the gesture category names. Each subdirectory would contain 32 additional folders that referred to one sample of the input. These folders would store the sequence of images. I used 8 images per image sequence. To obtain these images I used the following script:</p><pre>import mediapipe as mp<br>import cv2<br>import os<br><br>mp_drawing = mp.solutions.drawing_utils<br>mp_hands = mp.solutions.hands<br>subdir = &#39;hand_down&#39;                # specify which hand gesture directory to save the image sequences<br>n_frames_save = 8                   # specify how many frames in one sequence you wish to save<br>iteration_counter = n_frames_save + 1<br>folder_counter = 1<br><br>capture = cv2.VideoCapture(0)<br><br>with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands:<br>    while capture.isOpened():<br>        ret, frame = capture.read()<br>        image = cv2.flip(frame, 1)<br>        detected_image = hands.process(image)<br><br>        if detected_image.multi_hand_landmarks:<br>            for hand_lms in detected_image.multi_hand_landmarks:<br>                mp_drawing.draw_landmarks(image, hand_lms,<br>                                          mp_hands.HAND_CONNECTIONS,<br>                                          landmark_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                              color=(255, 0, 255), thickness=4, circle_radius=2),<br>                                          connection_drawing_spec=mp.solutions.drawing_utils.DrawingSpec(<br>                                              color=(20, 180, 90), thickness=2, circle_radius=2)<br>                                          )<br><br>        cv2.imshow(&#39;Webcam&#39;, image)<br><br>        if cv2.waitKey(10) &amp; 0xFF == ord(&#39;r&#39;):<br>            seq_folder_path = os.path.join(&#39;data&#39;, subdir, f&#39;sequence{folder_counter}&#39;)<br>            os.mkdir(seq_folder_path)<br>            folder_counter += 1<br>            iteration_counter = 1<br><br>        if iteration_counter &lt; n_frames_save + 1:<br>            cv2.imwrite(os.path.join(seq_folder_path, f&#39;{subdir}_sequence{folder_counter}_frame{iteration_counter}.jpg&#39;), image)<br>            if iteration_counter == n_frames_save:<br>                print(f&#39;Images for sequence {folder_counter - 1} saved.&#39;)<br>            iteration_counter += 1<br><br>        if cv2.waitKey(10) &amp; 0xFF == ord(&#39;q&#39;):<br>            break<br><br>capture.release()<br>cv2.destroyAllWindows()</pre><p>The os library allows me to access the files and folders. When ‘R’ is pressed, the program saves the next 8 frames (specified by n_frames_save variable) in a new folder inside the gesture category subdirectory specified by the subdir variable. So I had to save those new folders 32 times for each gesture type. To save the data for the next model, I had to stop the program, change the subdir variable, and run the program again. After pressing ‘R’, I performed a downward motion with my hand (as hand_down category was first). However, a problem occurred where the program was unable to draw the landmarks for every frame when I was moving my hand. So I decided to remove the landmarks completely. To improve the data quality, I saved the images in different backgrounds, performed the action with both hands, and included my face in some of the images while excluding in others.</p><h3>Building the Model</h3><p>So now I had my data in the form of image sequences where I did not include the landmarks. I knew I would have to use a convolutional neural network to process the spatial features in the images. Moreover, since I used a sequence of images, I would also have to include LSTM layers to process the temporal features from the images. Keras had three kinds of layers that could be used to build the necessary neural network model: ConvLSTM2D and Conv2D with LSTM (aka LCRN). Here are their code snippets:</p><p>Conv2D w/ LSTM (LCRN)</p><pre># Conv2D w/ LSTM (LCRN)<br><br>import os<br>import cv2<br>import imgaug.augmenters as iaa<br>import pandas as pd<br>import numpy as np<br>import tensorflow as tf<br>import random<br>import datetime as dt<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from tensorflow.python.keras.layers import *<br>from tensorflow.keras.layers import *<br><br>with tf.device(&#39;/GPU:0&#39;):<br>    all_data_dir = &#39;data&#39;<br>    image_height, image_width = 120, 160<br>    sequence_length = 8<br>    X, y = [], []<br><br>    image_seq_augmenter = iaa.Sequential([<br>        iaa.Fliplr(0),<br>        iaa.Crop(percent=(0, 0.1)),<br>        iaa.LinearContrast((0.75, 1.5)),<br>        iaa.GaussianBlur(sigma=(0.0, 1.0)),<br>        iaa.Multiply((0.8, 1.2), per_channel=0.2)<br>    ])<br><br>    for idx, class_name in enumerate(os.listdir(all_data_dir)):<br>        for image_seq_name in os.listdir(os.path.join(all_data_dir, class_name)):<br>            image_seq = []<br>            for frame_name in os.listdir(os.path.join(all_data_dir, class_name, image_seq_name)):<br>                frame = cv2.imread(os.path.join(all_data_dir, class_name, image_seq_name, frame_name))<br>                frame = cv2.resize(frame, (image_height, image_width))<br>                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>                image_seq.append(frame)<br>            image_seq_aug = image_seq_augmenter(images=image_seq)<br>            X.extend([image_seq, image_seq_aug])<br>            y.extend([idx for i in range(2)])<br><br>    X = (np.array(X) / 255.0).astype(&#39;float32&#39;) # (n_samples, n_frames, height, width, channels)<br>    y = np.array(y)                             # (n_samples)<br><br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True, random_state=1)<br><br>    early_stopping = tf.keras.callbacks.EarlyStopping(restore_best_weights=True,<br>                                                      patience=10)<br><br>    model = tf.keras.Sequential([<br>        TimeDistributed(Conv2D(16, 3, activation=&#39;relu&#39;, input_shape=(sequence_length, image_height, image_width, 3),<br>                   padding=&#39;same&#39;)),<br>        TimeDistributed(BatchNormalization()),<br>        TimeDistributed(MaxPooling2D()),<br>        TimeDistributed(Dropout(0.3)),<br><br>        TimeDistributed(Conv2D(32, 3, activation=&#39;relu&#39;, padding=&#39;same&#39;)),<br>        TimeDistributed(BatchNormalization()),<br>        TimeDistributed(MaxPooling2D()),<br>        TimeDistributed(Dropout(0.3)),<br><br>        TimeDistributed(Conv2D(64, 3, activation=&#39;relu&#39;, padding=&#39;same&#39;)),<br>        TimeDistributed(BatchNormalization()),<br>        TimeDistributed(MaxPooling2D()),<br>        TimeDistributed(Dropout(0.3)),<br><br>        TimeDistributed(Conv2D(64, 3, activation=&#39;relu&#39;, padding=&#39;same&#39;)),<br>        TimeDistributed(BatchNormalization()),<br>        TimeDistributed(MaxPooling2D()),<br>        TimeDistributed(Dropout(0.3)),<br><br>        TimeDistributed(Flatten()),<br>        LSTM(32),<br>        Dense(4),<br>    ])<br><br>    model.compile(<br>        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),<br>        optimizer=tf.keras.optimizers.Adam(),<br>        metrics=[&#39;accuracy&#39;],<br>    )<br><br>    model_train_hist = model.fit(<br>        X_train, y_train,<br>        shuffle=True,<br>        batch_size=4,<br>        epochs=70,<br>        validation_split=0.2,<br>        callbacks=[early_stopping],<br>    )<br><br>    model_eval_loss, model_eval_acc = model.evaluate(X_test, y_test)<br>    date_time_format = &#39;%Y_%m_%d__%H_%M_%S&#39;<br>    current_date_time_dt = dt.datetime.now()<br>    current_date_time_str = dt.datetime.strftime(current_date_time_dt, date_time_format)<br><br>    model_name = f&#39;model__date_time_{current_date_time_str}__loss_{model_eval_loss}__acc_{model_eval_acc}__hand.h5&#39;<br>    model.save(model_name)<br><br>    df_train_hist = pd.DataFrame(model_train_hist.history)<br>    df_train_hist.loc[:, [&#39;loss&#39;, &#39;val_loss&#39;]].plot()<br>    plt.show()</pre><p>ConvLSTM2D</p><pre># ConvLSTM2D<br><br>import os<br>import cv2<br>import imgaug.augmenters as iaa<br>import pandas as pd<br>import numpy as np<br>import tensorflow as tf<br>import random<br>import datetime as dt<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from tensorflow.python.keras.layers import *<br>from tensorflow.keras.layers import *<br><br>with tf.device(&#39;/GPU:0&#39;):<br>    all_data_dir = &#39;data&#39;<br>    image_height, image_width = 120, 160<br>    sequence_length = 8<br>    X, y = [], []<br><br>    image_seq_augmenter = iaa.Sequential([<br>        iaa.Fliplr(0),<br>        iaa.Crop(percent=(0, 0.1)),<br>        iaa.LinearContrast((0.75, 1.5)),<br>        iaa.GaussianBlur(sigma=(0.0, 1.0)),<br>        iaa.Multiply((0.8, 1.2), per_channel=0.2)<br>    ])<br><br>    for idx, class_name in enumerate(os.listdir(all_data_dir)):<br>        for image_seq_name in os.listdir(os.path.join(all_data_dir, class_name)):<br>            image_seq = []<br>            for frame_name in os.listdir(os.path.join(all_data_dir, class_name, image_seq_name)):<br>                frame = cv2.imread(os.path.join(all_data_dir, class_name, image_seq_name, frame_name))<br>                frame = cv2.resize(frame, (image_height, image_width))<br>                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)<br>                image_seq.append(frame)<br>            image_seq_aug = image_seq_augmenter(images=image_seq)<br>            X.extend([image_seq, image_seq_aug])<br>            y.extend([idx for i in range(2)])<br><br>    X = (np.array(X) / 255.0).astype(&#39;float32&#39;) # (n_samples, n_frames, height, width, channels)<br>    y = np.array(y)                             # (n_samples)<br><br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True, random_state=1)<br><br>    early_stopping = tf.keras.callbacks.EarlyStopping(restore_best_weights=True,<br>                                                      patience=10)<br><br>    model = tf.keras.Sequential([<br>        ConvLSTM2D(8, 3, activation=&#39;tanh&#39;, input_shape=(sequence_length, image_height, image_width, 3),<br>                   return_sequences=True, data_format=&#39;channels_last&#39;, recurrent_dropout=0.3),<br>        BatchNormalization(),<br>        MaxPooling3D(pool_size=(1, 2, 2), padding=&#39;same&#39;, data_format=&#39;channels_last&#39;),<br>        TimeDistributed(Dropout(0.3)),<br>    <br>        ConvLSTM2D(8, 3, activation=&#39;tanh&#39;, return_sequences=True,<br>                   data_format=&#39;channels_last&#39;, recurrent_dropout=0.3),<br>        BatchNormalization(),<br>        MaxPooling3D(pool_size=(1, 2, 2), padding=&#39;same&#39;, data_format=&#39;channels_last&#39;),<br>        TimeDistributed(Dropout(0.3)),<br>    <br>        ConvLSTM2D(16, 3, activation=&#39;tanh&#39;, return_sequences=True,<br>                   data_format=&#39;channels_last&#39;, recurrent_dropout=0.3),<br>        BatchNormalization(),<br>        MaxPooling3D(pool_size=(1, 2, 2), padding=&#39;same&#39;, data_format=&#39;channels_last&#39;),<br>        TimeDistributed(Dropout(0.3)),<br>    <br>        ConvLSTM2D(20, 3, activation=&#39;tanh&#39;, return_sequences=True,<br>                   data_format=&#39;channels_last&#39;, recurrent_dropout=0.3),<br>        BatchNormalization(),<br>        MaxPooling3D(pool_size=(1, 2, 2), padding=&#39;same&#39;, data_format=&#39;channels_last&#39;),<br>        TimeDistributed(Dropout(0.3)),<br>    <br>        Flatten(),<br>        Dense(64, activation=&#39;relu&#39;),<br>        Dropout(0.3),<br>        Dense(32, activation=&#39;relu&#39;),<br>        Dense(4),<br>    ])<br><br>    model.compile(<br>        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),<br>        optimizer=tf.keras.optimizers.Adam(),<br>        metrics=[&#39;accuracy&#39;],<br>    )<br><br>    model_train_hist = model.fit(<br>        X_train, y_train,<br>        shuffle=True,<br>        batch_size=4,<br>        epochs=70,<br>        validation_split=0.2,<br>        callbacks=[early_stopping],<br>    )<br><br>    model_eval_loss, model_eval_acc = model.evaluate(X_test, y_test)<br>    date_time_format = &#39;%Y_%m_%d__%H_%M_%S&#39;<br>    current_date_time_dt = dt.datetime.now()<br>    current_date_time_str = dt.datetime.strftime(current_date_time_dt, date_time_format)<br><br>    model_name = f&#39;model__date_time_{current_date_time_str}__loss_{model_eval_loss}__acc_{model_eval_acc}__hand.h5&#39;<br>    model.save(model_name)<br><br>    df_train_hist = pd.DataFrame(model_train_hist.history)<br>    df_train_hist.loc[:, [&#39;loss&#39;, &#39;val_loss&#39;]].plot()<br>    plt.show()</pre><p>The line with tf.device(‘/GPU:0’): indicates that the code in this block will be executed using the GPU (remove it if you are using CPU). The LCRN model trained in less than 5 minutes (with GPU), much faster than ConvLSTM2D which took an hour to train. Additionally, LCRN had higher accuracy. For these reasons, I continued to use this model. I used the imgaug library to perform data augmentation on the images to make them more diverse and make the model more robust. Additionally, these augmentations doubled the data sample size. However, I couldn’t use the horizontal flipping data augmentation as the left and the right hand motions would become mixed. The data that was used to train the model was in the form of NumPy arrays. Array X had the following shape: (no. of samples, no. of frames, height, width, channels). The array y had the shape (no. of samples,) and contained the labels for the gestures in the form of numbers from 0 to 3 (down, left, right, up). Theearly_stopping variable stops the model training before it trains for the prescribed number of epochs if the validation loss of the model does not improve significantly after a certain number of epochs. It also selects the best weights for the model from the training and helps prevent overfitting. I included the TimeDistributed layer in LCRN because the Conv2D layers accept only one image as input. This layer allows every image in the image sequence to enter the convolutional layers independently. I saved the trained models so I don’t have to train them every time I want to use them. I used the datetime library to include the date and time the model was saved.</p><p>When training with the GPU, OOM errors were encountered. To overcome these errors, I could switch to using Google Colab or switch to using CPU which had more RAM. However, I decided to just decrease the resolution of the images by resizing so that they occupy less space in memory.</p><h3>Testing the Model</h3><p>After the training had finished, I decided to generate a few more samples of different gestures to see if the model could predict which gesture I was performing. I quickly came to realize that 8 frames were not enough to capture the entire motion of the hand. The last frame showed that the hand was still in the middle of the motion. Additionally, the predictions of the new samples were mostly wrong. I thought that the problem was that the number of frames was too small for it to understand. So my next objective is to retry the training and testing by using more than 8 frames per image sequence.</p><h3>Refining the Model</h3><p>I had to generate new images since the old ones had 8 frames and could not be used anymore. I increased the number of frames to 20 and used 16 samples per gesture category as I thought that would be enough. I also tried to capture them using a new webcam that produced better quality and had a higher frame rate. I just changed the linecapture = cv2.VideoCapture(1) from 0 to 1 to use this webcam. However, for some reason, the new webcam took significantly longer to open the webcam window compared to the integrated one. After retraining and retesting the model, the predictions were yet again unsatisfactory and were mostly wrong. In both cases, I included the entire image in the data. The background and the fact that the model does not know which part of the image is the hand could have affected the performance. So a possible solution was to apply image segmentation to the hand such that the hand would look white while the rest of the image would appear black.</p><p>Click <a href="https://medium.com/@odil.tokhirov/how-i-built-a-hand-gesture-recognition-model-in-python-part-2-5d8987bb0756">here</a> for part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db378cf196e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deal with missing and categorical values in data used for machine learning?]]></title>
            <link>https://medium.com/@odil.tokhirov/how-to-deal-with-missing-and-categorical-values-in-data-used-for-machine-learning-28e8b95539bf?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/28e8b95539bf</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[missing-values]]></category>
            <category><![CDATA[categorical-encoding]]></category>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 03:43:52 GMT</pubDate>
            <atom:updated>2023-10-03T11:39:59.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wtKzcwV8wtn05seSaMh3w.jpeg" /><figcaption>Image by <a href="https://www.freepik.com/free-photo/modern-equipped-computer-lab_21797023.htm#query=computer%20data&amp;position=2&amp;from_view=search&amp;track=ais">Freepik</a></figcaption></figure><p>Real-world data is rarely clean and may have missing values for some of the features for various reasons. Additionally, the data may be stored as strings representing different categories. Both of these entries may cause problems when trying to enter them into a machine-learning model. Hence, data preprocessing steps must be taken to avoid such errors.</p><h3>Missing Values</h3><p>Let’s say we have our data in the form of a table where the columns represent the different features and where the rows represent the data samples (instances). A missing value is considered as a value that is absent in one of the cells (blank). A machine learning model cannot use data that is absent. To solve this issue, we can either remove the row or column where the missing value lies, or we can impute its value.</p><p>Removing the entire row or column is a straightforward and easy method of dealing with missing values. However, unless the majority of values in a particular row or column are missing, this is not a good strategy as lots of potentially useful information is lost. As such, we usually impute the missing values.</p><p>Imputing a value means that we are predicting it by considering the other values in its column. For example, if we have a dataset with a numerical feature called ‘size’, we can predict the missing values by calculating the mean of the other present values. Alternatively, one may choose to impute by using the median or the mode of the values, or by setting a constant value. Through imputation, we can obtain reasonable estimates for the missing values.</p><h3>Categorical Values</h3><p>Categorical values have a discrete and finite number of possible values. For example, a feature called ‘type of material’ can have distinct values such as ‘paper’, ‘plastic’, and ‘metal’. Input that goes into machine learning models needs to be in the form of numbers instead of strings (in most cases). To convert the strings into a numerical format we must encode them. One may choose to either use ordinal encoding or one-hot encoding.</p><p>One-hot encoding converts each category type in a feature into a separate feature that has binary values of either 1 (True) or 0 (False). For example, if we one-hot encode the above ‘type of material’ column, we would get three separate columns that we can call ‘paper’, ‘plastic’, and ‘metal’ where 1 would mean that the sample is of that material type with all the other new columns having a value of 0. This is shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*XRoy9lbWZHrOLoPHhkwf8A.png" /><figcaption>One-Hot Encoding</figcaption></figure><p>The number of newly derived columns equals the number of different types of categorical values. So if we have lots of different possible categorical values for a certain feature, we will have a larger file upon one-hot encoding. This is the downside of one-hot encoding where more memory and computational power are required if lots of additional columns are made.</p><p>Another form of encoding is called ordinal encoding where the categorical values are turned into numbers (from 0 to some positive integer). This is usually used when the values have an ordered relationship between them. Suppose we have a feature called ‘condition’ with the following possible values: ‘very bad’, ‘bad’, ‘satisfactory’, ‘good’, and ‘excellent’. In this case, we can ordinally encode the values to range from 0 to 4 where 0 represents the lower end of the spectrum (‘very bad’) and 4 represents the highest value (‘excellent’). This is shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3SzEbcg3Gtt6hSIqYf6p4g.png" /><figcaption>Ordinal Encoding</figcaption></figure><h3>When to apply?</h3><p>When you only have one dataset, you will have to split the data into training and test sets (and validation if you want to). It is important to understand when to preprocess the data relative to when you split the data.</p><p>If you want to encode the categorical features in your dataset, it is better to do so before splitting your data (correct me if I’m wrong). This ensures that no problem arises where certain categorical values appear in the test set while being absent in the training set. For example, if we instead encoded the data after splitting, the value ‘excellent’ of the ‘condition’ feature may have been absent from the training data. So when it appears in the test data, the program won’t know which numerical value to assign to it.</p><p>On the other hand, if you wish to impute the missing values in your dataset, then you must do so after splitting the data. This avoids something called data leakage. If we instead imputed all the missing values before splitting, then we would be including the test set data to help predict the unknown values in the training set (and vice versa). This may cause the model to perform better than it actually is, as, in a way, it has seen a part of the test data.</p><h4>Conclusion</h4><p>In summary, delete or impute missing values, use one-hot or ordinal encoding for categorical values, and if you have one dataset then encode before and impute after splitting the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e8b95539bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does a Convolutional Neural Network work?]]></title>
            <link>https://medium.com/@odil.tokhirov/how-does-a-convolutional-neural-network-work-a64d47b22c46?source=rss-11ba1eecac62------2</link>
            <guid isPermaLink="false">https://medium.com/p/a64d47b22c46</guid>
            <category><![CDATA[convolutional-neural-net]]></category>
            <dc:creator><![CDATA[Odilbek Tokhirov]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 03:14:32 GMT</pubDate>
            <atom:updated>2023-10-03T11:13:00.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0qBsYr20EsabsxBUXevUw.jpeg" /><figcaption><a href="https://www.freepik.com/free-vector/abstract-mesh-background_1534336.htm#query=neural%20network&amp;position=3&amp;from_view=search&amp;track=ais">Image by GarryKillian</a> on Freepik</figcaption></figure><p>A convolutional neural network is a type of deep learning algorithm that is mainly used to perform computer vision tasks. It consists of the convolutional and pooling layers.</p><p>An image is inputted into the network as a 3D array having the following shape: (height, width, color channel). The height and width of the image specify the number of pixels present along these dimensions. The color channel specifies the number of different color types the pixels will represent. Usually, if the number of channels is one, the pixels will have greyscale values. If RGB images are used, there would be three color channels that represent the red, green, and blue shades.</p><h3>Convolutional Layer</h3><p>A convolutional layer is a collection of filters (aka kernels). A filter is a matrix of numbers, usually of size 3×3. These numbers are the weights that are computed when the neural network is trained. The filters are responsible for extracting certain features from the input image such as edges and corners. Each filter slides across the input image and produces new numbers in a new 3D array (which is the output of the convolutional layer). The new numbers are the dot product of the filter’s weights and the pixel values of the image (this is called convolution). The new 3D array is called a feature map. The number of feature maps is equal to the number of filters present in a certain convolutional layer. Therefore the output of a convolutional layer is a 3D array with the shape (height, width, no. of feature maps).</p><p>In addition to the number of filters and filter size hyperparameters, convolutional layers can be configured to change their padding and stride. When a filter performs a dot product on an input image (or feature maps for later convolutional layers), the height and width of the output 3D array will be less than the input. This happens because a filter with a size of 3x3 converts a 3x3 area of an input image into one value in the output. One may choose to prevent this decrease in output size by changing the parameter called padding. Padding is a process that makes new zero-pixel values around the input image such that the height and width of the output will be the same as the input. Padding can be set to be ‘valid’ or ‘same’. A ‘valid’ padding indicates that no padding will be applied, whereas the ‘same’ padding indicates that the height and width of the input and the output should be the same (by applying padding).</p><p>The stride hyperparameter indicates the number of pixel values for the filter to jump before calculating the dot product. Increasing the stride more than the kernel size will cause some of the pixel values to be skipped which leads to loss of information. As such, it is recommended to keep the stride on the lower end.</p><h3>Pooling Layer</h3><p>The pooling layer decreases the resolution of the feature maps by passing a filter with an area of 2x2 pixels and converting them into one pixel. This can be done either by choosing the value of the maximum pixel (max pooling) or by calculating the average value of all the pixels inside the filter’s area (average pooling). Unlike the filters of the convolutional layer, the filters of the pooling layers do not have weights associated with them. The pool size can be changed to include more pixels in the filter’s window (for example to include a 4x4 area). Pooling an image decreases the amount of computation required. Additionally, small changes in the original image will be ignored since the pooled image does not account for every pixel change in the original one.</p><p>To better understand the above concepts, I highly recommend watching the videos prepared by the following YouTube Channel which helped me to visualize and understand them as well: <a href="https://www.youtube.com/@animatedai">https://www.youtube.com/@animatedai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a64d47b22c46" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>