<?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 hoggyna on Medium]]></title>
        <description><![CDATA[Stories by hoggyna on Medium]]></description>
        <link>https://medium.com/@hoggyna?source=rss-881fb39798e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by hoggyna on Medium</title>
            <link>https://medium.com/@hoggyna?source=rss-881fb39798e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:19:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hoggyna/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[Brain Code Camp]]></title>
            <link>https://hoggyna.medium.com/brain-code-camp-5276f7294fac?source=rss-881fb39798e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5276f7294fac</guid>
            <dc:creator><![CDATA[hoggyna]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 13:48:53 GMT</pubDate>
            <atom:updated>2023-11-03T13:48:53.782Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>สวัสดีครับ! โปรเจกต์นี้เป็นส่วนหนึ่งของโครงการ </em>Brain Code Camp<em> 2023 โดยโปรเจกนี้เป็นการเรียนรู้ความจำของสมองโดยอ้างอิงจากงานวิจัยของ </em>Neural Differentiation of Incorrectly Predicted Memorie <em>และนำมาศึกษาต่อ</em></strong></blockquote><p>อ้างอิงจากงานวิจัย <a href="https://www.jneurosci.org/content/37/8/2022#abstract-1">https://www.jneurosci.org/content/37/8/2022#abstract-1</a></p><p>ศึกษาและฝึกทำโค๊ดจาก <a href="https://brainiak.org/tutorials/03-classification/">https://brainiak.org/tutorials/03-classification/</a></p><p>โดยการทำโปรเจกต์ในครั้งนี้มีเป้าหมายอยู่ 3 อย่างคือ<br>1.<strong>FFA decoding (</strong> Decode Objects vs. Scenes from the FFA and report mean LORO test accuracy.<strong>)<br>2.PPA decoding(</strong> Decode Objects vs. Faces from the PPA and report mean LORO test accuracy.<strong>)<br>3.Compare with FFA vs PPA use </strong>LinearSVC</p><h3><strong>ขั้นตอนการทำ</strong></h3><p>เริ่มส่วนของการเขียนโค๊ด (coding) โดยในครั้งนี้ผมทำด้วย google colab<br>install libray และ import ฟังชั่นที่จะใช้ทั้งหมด</p><pre>!pip install -U brainiak<br><br>!git clone https://github.com/brainiak/brainiak-tutorials.git<br>!cd brainiak-tutorials/tutorials/; cp -r 07-searchlight 09-fcma 13-real-time utils.py setup_environment.sh /content/<br># Make brainiak_datasets sub-directory in home directory<br>!mkdir /root/brainiak_datasets<br><br>!mkdir -p /root/brainiak_datasets<br><br>!cd /root/brainiak_datasets; wget -q --show-progress --no-check-certificate -r &#39;https://drive.google.com/uc?id=1tiEjtp96zwIdnl3p726llj5KMETnNJ4A&amp;export=download&#39; -O &#39;02-data-handling-simulated-dataset.zip&#39;<br>!cd /root/brainiak_datasets; unzip 02-data-handling-simulated-dataset.zip<br>!cd /root/brainiak_datasets; wget -q --show-progress --no-check-certificate -r &#39;https://drive.google.com/uc?export=download&amp;confirm=KlKd&amp;id=1PrnucQ4hXqUY8gl6ysGJJiTreYu7KOLz&#39; -O &#39;vdc.zip&#39;<br>!cd /root/brainiak_datasets; unzip vdc.zip<br><br>!pip install nilearn</pre><pre>import warnings<br>import sys <br>if not sys.warnoptions:<br>    warnings.simplefilter(&quot;ignore&quot;)<br>import os <br>import nibabel as nib<br>import numpy as np<br>from nilearn.input_data import NiftiMasker<br>import scipy.io<br>from scipy import stats<br>import matplotlib.pyplot as plt<br>import seaborn as sns <br><br>from sklearn.svm import LinearSVC<br>from sklearn.model_selection import PredefinedSplit<br>from sklearn.preprocessing import StandardScaler<br>from brainiak.utils.fmrisim import _double_gamma_hrf as hrf_func<br>from brainiak.utils import fmrisim as sim<br><br># load some helper functions<br>from utils import load_vdc_mask, load_vdc_epi_data, load_vdc_masked_data <br>from utils import vdc_data_dir, vdc_all_ROIs, vdc_label_dict, vdc_n_runs, vdc_hrf_lag, vdc_TR, vdc_TRs_run # load some constants<br><br>%matplotlib inline <br>%autosave 5<br>sns.set(style = &#39;white&#39;, context=&#39;poster&#39;, rc={&quot;lines.linewidth&quot;: 2.5})<br>sns.set(palette=&quot;colorblind&quot;)</pre><p>ทดสอบข้อมูลในโฟลเดอร์ที่ดาวโหลดมา</p><pre># Set the variables<br>sub = &#39;sub-01&#39;;<br><br># Preset the variable size<br>stim_label = [];<br>stim_label_allruns = [];<br>for run in range(1, vdc_n_runs+1):<br><br>    # Specify the input variables<br>    in_file = os.path.join(vdc_data_dir,sub,&#39;ses-day2&#39;,&#39;design_matrix&#39;,&#39;%s_localizer_0%d.mat&#39; % (sub, run))<br><br>    # Load in data from MATLAB<br>    stim_label = scipy.io.loadmat(in_file);<br>    stim_label = np.array(stim_label[&#39;data&#39;]);<br><br>    # Store the data<br>    if run == 1:<br>        stim_label_allruns = stim_label;<br>    else:<br>        stim_label_allruns = np.hstack((stim_label_allruns, stim_label))<br><br>print(&quot;Loaded labels for&quot;, sub)</pre><p>สร้างฟังชั่น <em>load_vdc_stim_labels</em> ไว้คอยดาวโหลดข้อมูลที่อยู่ในโฟลเดอร์</p><pre># Make a function for loading in the labels<br>def load_vdc_stim_labels(vdc_data_dir, subject_id):<br>    stim_label = [];<br>    stim_label_concatenated = [];<br>    for run in range(1, vdc_n_runs+1):<br>        in_file = os.path.join(vdc_data_dir,subject_id,&#39;ses-day2&#39;,&#39;design_matrix&#39;,&#39;%s_localizer_0%d.mat&#39; %<br>                               (subject_id, run))<br>        # Load in data from MATLAB<br>        stim_label = scipy.io.loadmat(in_file);<br>        stim_label = np.array(stim_label[&#39;data&#39;]);<br><br>        # Store the data<br>        if run == 1:<br>            stim_label_concatenated = stim_label;<br>        else:<br>            stim_label_concatenated = np.hstack((stim_label_concatenated, stim_label))<br>    print(&quot;Loaded labels for&quot;, subject_id)<br>    return stim_label_concatenated<br><br># Note: you won&#39;t see the printed &quot;Loaded labels for...&quot; until you run the function with inputs (see next step)</pre><p>สร้างฟังชั่น label2TR เพื่อกำหนดหมวดหมู่สำหรับทุกจุดเวลา ( label TR) ในข้อมูล fMRI จุดเวลาเหล่านี้เรียกอีกอย่างว่า TR</p><pre>def label2TR(stim_labels, num_runs, TR, TRs_run):<br>    _, events = stim_labels.shape<br>    events_run = int(events / num_runs)<br>    stim_label_TR = np.zeros((TRs_run * num_runs, 1))<br><br>    for run in range(num_runs):<br>        for i in range(events_run):<br>            time_idx = run * (events_run) + i<br>            time = stim_labels[2, time_idx]<br>            TR_idx = int(time / TR) + (run * (TRs_run - 1))<br>            stim_label_TR[TR_idx] = stim_labels[0, time_idx]<br><br>    return stim_label_TR</pre><p>แสดงข้อมูลใน fMRI โดยมี 1.วัตถุ 2.สถานที่ 3.รูปคน</p><pre>n_conditions = len(vdc_label_dict)<br>cur_pals = sns.color_palette(&#39;colorblind&#39;, n_colors=n_conditions)<br><br># Create a sequence of timepoints that a TR occurred on<br>tr_time = np.arange(0, (vdc_TRs_run - 1) * 1.5 + 1, 1.5)<br>time_vals = stim_label_allruns[2, 0:150]<br>labels = stim_label_allruns[0, 0:150]<br><br>f, ax = plt.subplots(1,1, figsize = (14, 5))<br><br># plot the label for each condition<br>for i_cond in range(n_conditions):<br>    label = list(vdc_label_dict.keys())[i_cond]<br>    temp_mask = label == labels<br>    ax.scatter(time_vals[temp_mask], labels[temp_mask],<br>               color = cur_pals[i_cond], marker = &#39;o&#39;)<br>ax.legend(vdc_label_dict.values())<br><br># plot the stimuli as a line<br># ax.plot(time_vals, labels, color = &#39;black&#39;, alpha = .5)<br>ax.plot(tr_time, stim_label_TR[0:vdc_TRs_run, 0], c=&#39;orange&#39;, alpha = .5)<br><br>ax.set_yticks(list(vdc_label_dict.keys()))<br>ax.set_yticklabels(vdc_label_dict.values())<br><br>ax.set_title(&#39;Stimulus Presentation for Run 1&#39;)<br>ax.set_xlabel(&#39;Time in secs&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiZ9KVsIFwtK4RRXCApaeg.png" /></figure><p>เราจำเป็นต้องแยกสัญญาณ เพื่อจำแนกประเภท (เพื่อให้ป้ายกำกับใช้กับภาพสมองที่ถูกต้อง) เมื่อพิจารณาว่า TR หนึ่งอัน = 1.5 วินาที และความล่าช้าของสัญญาณทั่วไปคือ 4–5 วินาที เราจะเลื่อนป้ายกำกับไปข้างหน้า 3 TR โดยสร้างฟังชั่น shift_timing ขึ้นมา</p><pre># Shift the data a certain amount<br>print(&#39;Amount of time shift: %0.1f&#39; % vdc_hrf_lag) # In seconds what is the lag between a stimulus onset and the peak bold response<br>shift_size = int(vdc_hrf_lag / vdc_TR)  # Convert the shift into TRs<br><br># Create a function to shift the size<br>def shift_timing(label_TR, TR_shift_size):<br><br>    # Create a short vector of extra zeros<br>    zero_shift = np.zeros((TR_shift_size, 1))<br><br>    # Zero pad the column from the top<br>    label_TR_shifted = np.vstack((zero_shift, label_TR))<br><br>    # Don&#39;t include the last rows that have been shifted out of the time line<br>    label_TR_shifted = label_TR_shifted[0:label_TR.shape[0],0]<br><br>    return label_TR_shifted<br><br># Apply the function<br>stim_label_TR_shifted = shift_timing(stim_label_TR, shift_size)</pre><pre>f, ax = plt.subplots(1,1, figsize = (12,5))<br>ax.plot(tr_time, stim_label_TR[0:vdc_TRs_run, 0], c=&#39;blue&#39;,alpha=0.2)<br>ax.plot(tr_time, stim_label_TR_shifted[0:310], c=&#39;orange&#39;)<br><br>ax.set_yticks(list(vdc_label_dict.keys()))<br>ax.set_yticklabels(vdc_label_dict.values())<br><br>ax.set_ylabel(&#39;Stimuli labels&#39;)<br>ax.set_xlabel(&#39;Time in secs&#39;)<br><br>plt.legend([&#39;Original&#39;, &#39;Shifted&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNpD-AsYbFAyWPTKCDJV-Q.png" /></figure><p>ในขั้นตอนต่อมาจะ Classification ข้อมูล<br>โดยเราจะกำหนดข้อมูลออกมาเป็นอย่างแรก</p><pre>roi_name = &#39;FFA&#39; #อยากใช้ข้อมูลส่วนไหนก็ comment บรรทัดที่ไม่ใช้<br>roi_name = &#39;PPA&#39;<br><br># Apply the function to pull out the mask data<br>epi_mask_data_all = load_vdc_masked_data(vdc_data_dir, sub, vdc_all_ROIs)<br><br># Check the dimensionality of the data<br>print(&#39;voxel by TR matrix - shape: &#39;, epi_mask_data_all[vdc_all_ROIs.index(roi_name)].shape)<br>print(&#39;label list - shape: &#39;, stim_label_TR_shifted.shape)</pre><p>ในลำดับต่อมา สร้างฟังชั่น reshape_data เพื่อที่เราจะแยกจุดเวลาที่เรามีป้ายกำกับสิ่งกระตุ้น (เฉพาะใบหน้า สถานที่ และวัตถุ) นั่นคือเรายกเลิกจุดเวลาจากสัญญาณ ที่อ้างอิงถึง ณ ช่วงเวลาที่คงที่</p><pre># Extract bold data for non-zero labels<br>def reshape_data(label_TR_shifted, masked_data_all):<br>    label_index = np.nonzero(label_TR_shifted)<br>    label_index = np.squeeze(label_index)<br>    # Pull out the indexes<br>    indexed_data = np.transpose(masked_data_all[:,label_index])<br>    nonzero_labels = label_TR_shifted[label_index]<br>    return indexed_data, nonzero_labels<br><br># Pull out the data from this ROI for these time points<br>roi_masked_data = epi_mask_data_all[vdc_all_ROIs.index(roi_name)]<br>bold_data, labels = reshape_data(stim_label_TR_shifted, roi_masked_data)<br><br># What is the dimensionality of the data? We need the first dim to be the same<br>print(&#39;The %s has the dimensionality of: %d time points by %d voxels&#39; % (roi_name, bold_data.shape[0], bold_data.shape[1]))</pre><p>โดยการ Classifiers ในครั้งนี้เราจะใช้ LinearSVC เป็นตัวคัดแยกให้กับเรา</p><p>แบ่งข้อมูลออกมาสำหรับเทรนโมเดล</p><pre>X_train = bold_data_normalized[train_runs,]<br>y_train = labels[train_runs]<br>X_test = bold_data_normalized[np.logical_not(train_runs),]<br>y_test = labels[np.logical_not(train_runs)]</pre><pre># loop over all runs<br>scores = []<br><br># split data according to run ids<br>ps = PredefinedSplit(run_ids)<br><br># classifier<br>model = LinearSVC()<br>for train_index, test_index in ps.split():<br>    X_train, X_test = bold_data_normalized[train_index], bold_data_normalized[test_index]<br>    y_train, y_test = labels[train_index], labels[test_index]<br><br>    # fit an svm<br>    model.fit(X_train, y_train)<br><br>    # calculate the accuracy for the hold out run<br>    score = model.score(X_test, y_test)<br>    scores.append(score)<br><br>print(&#39;Accuracy across folds:&#39;, scores)</pre><p>Accuracy across folds: [0.88, 0.8933333333333333, 0.8466666666666667]</p><p>เพื่อให้เกิดความสะดวกใากยิ่งขึ้นเราจะสร้างฟังชั่น decode ออกมาเพื่อให้การเทรนโมเดลของเรามีความสะดวกมากยิ่งขึ้น</p><pre># Put code here. The function should output models and scores<br>def decode(data, labels, run_labels):<br>    # loop over all runs<br>    scores = []<br><br>    # split data according to run ids<br>    ps = PredefinedSplit(run_labels)<br><br>    # classifier<br>    model = LinearSVC()<br>    for train_index, test_index in ps.split():<br>        X_train, X_test = data[train_index], data[test_index]<br>        y_train, y_test = labels[train_index], labels[test_index]<br><br>        # fit an svm<br>        model.fit(X_train, y_train)<br><br>        # calculate the accuracy for the hold out run<br>        score = model.score(X_test, y_test)<br>        scores.append(score)<br><br>    return model, scores</pre><h3>การทำ FFA และ PPA decoding</h3><p>เตรียมข้อมูลเพื่อทำการFFA(มีสถานที่ , วัตถุ)และ PPA decoding (มีวัตถุ , รูปคน)</p><pre># choose a subject<br>sub = &#39;sub-01&#39;;<br><br># Convert the shift from secs to TRs<br>shift_size = int(vdc_hrf_lag / vdc_TR)<br><br># Load subject labels<br>stim_label_allruns = load_vdc_stim_labels(vdc_data_dir,sub)<br><br># Load the fMRI data<br>epi_mask_data_all = load_vdc_masked_data(vdc_data_dir, sub, vdc_all_ROIs)<br><br># Convert the timing into TR indexes<br>TRs_run = int(epi_mask_data_all[0].shape[1] / vdc_n_runs)<br>stim_label_TR = label2TR(stim_label_allruns, vdc_n_runs, vdc_TR, TRs_run)<br><br># Shift the data some amount<br>stim_label_TR_shifted = shift_timing(stim_label_TR, shift_size)<br># Select and reshape FFA data<br>bold_data_FFA, labels = reshape_data(<br>    stim_label_TR_shifted, epi_mask_data_all[vdc_all_ROIs.index(&#39;FFA&#39;)])<br><br># Select and reshape PPA data<br>bold_data_PPA, _ = reshape_data(<br>    stim_label_TR_shifted, epi_mask_data_all[vdc_all_ROIs.index(&#39;PPA&#39;)])<br><br># Specify the classifiers that will be used<br>svc = LinearSVC()<br><br># load run ids (works similarity to cv_ids)<br>run_ids = stim_label_allruns[5,:] - 1</pre><p>FFA decoding</p><pre># Select a target<br>holdout_labels = 1 # 1 = face, 2 = scene, 3 = object<br><br># Make an index list with one label left out.<br>non_face_trials = labels != holdout_labels<br><br># Reduce an index of label corresponding to the bold data<br>labels_FFA = labels[non_face_trials]<br><br># Make an index list with one label left out.<br>run_ids_FFA = run_ids[non_face_trials]<br><br># Normalization of FFA bold data<br>bold_data_FFA_normalized = normalize(bold_data_FFA[non_face_trials,], run_ids_FFA)<br>models, scores = decode(bold_data_FFA_normalized, labels_FFA, run_ids_FFA)<br>print(&#39;Decoding accuracy across the 3 folds: &#39;, scores)</pre><pre>Decoding accuracy across the 3 folds:  [0.86, 0.87, 0.88]</pre><p>PPA decoding</p><pre># Select a target<br>holdout_labels = 2 # 1 = face, 2 = scene, 3 = object<br><br># Make an index list with one label left out.<br>non_place_trials = labels != holdout_labels<br><br># Reduce an index of label corresponding to the bold data<br>labels_PPA = labels[non_place_trials]<br><br># Make an index list with one label left out.<br>run_ids_PPA = run_ids[non_place_trials]<br><br># Normalization of FFA bold data<br>bold_data_PPA_normalized = normalize(bold_data_PPA[non_place_trials,], run_ids_PPA)<br>models, scores = decode(bold_data_PPA_normalized, labels_PPA, run_ids_PPA)<br>print(&#39;Decoding accuracy across the 3 folds: &#39;, scores)</pre><pre>Decoding accuracy across the 3 folds:  [0.66, 0.6, 0.64]</pre><h3>Compare with FFA vs PPA</h3><p>ในลำดับต่อมาเราจะทำโจทย์หัวข้อที่ 3 ก็คือ<strong>Compare with FFA vs PPA use </strong>LinearSVC</p><pre>all_sub = [&#39;sub-01&#39;,&#39;sub-02&#39;,&#39;sub-03&#39;]</pre><pre># Convert the shift from secs to TRs<br>shift_size = int(vdc_hrf_lag / vdc_TR)</pre><pre># Specify the classifiers that will be used<br>svc = LinearSVC()</pre><pre># General settings before loops<br>all_scores = np.zeros([3,4,3])<br>i = 0</pre><pre># Create dataframe to collect the results<br>classifier = {&#39;accuracy&#39;:[], &#39;sub&#39;:[], &#39;ROI&#39;:[], &#39;exclusion&#39;:[]}<br>df = pd.DataFrame(classifier)</pre><pre>for sub in all_sub:</pre><pre>    # Load subject labels<br>    stim_label_allruns = load_vdc_stim_labels(vdc_data_dir,sub)</pre><pre>    # Load the fMRI data<br>    epi_mask_data_all = load_vdc_masked_data(vdc_data_dir, sub, vdc_all_ROIs)</pre><pre>    # Convert the timing into TR indexes<br>    TRs_run = int(epi_mask_data_all[0].shape[1] / vdc_n_runs)<br>    stim_label_TR = label2TR(stim_label_allruns, vdc_n_runs, vdc_TR, TRs_run)</pre><pre>    # Shift the data some amount<br>    stim_label_TR_shifted = shift_timing(stim_label_TR, shift_size)</pre><pre>    for roi_name in vdc_all_ROIs:</pre><pre>        # Pull out the data from this ROI for these time points<br>        roi_masked_data = epi_mask_data_all[vdc_all_ROIs.index(roi_name)]<br>        bold_data, labels = reshape_data(stim_label_TR_shifted, roi_masked_data)</pre><pre>        # Select and reshape FFA data<br>        bold_data_FFA, _ = reshape_data(<br>            stim_label_TR_shifted, epi_mask_data_all[vdc_all_ROIs.index(&#39;FFA&#39;)])</pre><pre>        # Select and reshape PPA data<br>        bold_data_PPA, _ = reshape_data(<br>            stim_label_TR_shifted, epi_mask_data_all[vdc_all_ROIs.index(&#39;PPA&#39;)])</pre><pre>        #### General decoding for all classification ####<br>        # What is the dimensionality of the data? We need the first dim to be the same<br>        print(&#39;The %s has the dimensionality of: %d time points by %d voxels&#39; % (roi_name, bold_data.shape[0], bold_data.shape[1]))<br>        # load run ids (works similarity to cv_ids)<br>        run_ids = stim_label_allruns[5,:] - 1</pre><pre>        bold_data_normalized = normalize(bold_data, run_ids)</pre><pre>        models, scores = decode(bold_data_normalized, labels, run_ids)<br>        print(&#39;Decoding accuracy across the 3 folds: &#39;, scores)</pre><pre>        for x in range(vdc_n_runs):<br>            df.loc[i,&#39;accuracy&#39;] = scores[x]<br>            df.loc[i,&#39;sub&#39;] = sub<br>            df.loc[i,&#39;ROI&#39;] = roi_name<br>            df.loc[i,&#39;exclusion&#39;] = 0<br>            i+=1</pre><pre>        #### ROI parts for ROI decoding ####<br>        # Select a target 1 = face, 2 = scene, 3 = object<br>        if roi_name == &#39;FFA&#39;:<br>            holdout_labels = 1<br>            bold_data_XXA = bold_data_FFA<br>        elif roi_name == &#39;PPA&#39;:<br>            holdout_labels = 2<br>            bold_data_XXA = bold_data_PPA<br>        else:<br>            break</pre><pre>        # Make an index list with one label left out.<br>        non_x_trials = labels != holdout_labels</pre><pre>        # Reduce an index of label corresponding to the bold data<br>        labels_XXA = labels[non_x_trials]</pre><pre>        # Make an index list with one label left out.<br>        run_ids_XXA = run_ids[non_x_trials]</pre><pre>        # Normalization of FFA bold data<br>        bold_data_XXA_normalized = normalize(bold_data_XXA[non_x_trials,], run_ids_XXA)</pre><pre>        models, scores = decode(bold_data_XXA_normalized, labels_XXA, run_ids_XXA)<br>        print(&#39;Decoding accuracy across the 3 folds: &#39;, scores)</pre><pre>        for x in range(vdc_n_runs):<br>            df.loc[i,&#39;accuracy&#39;] = scores[x]<br>            df.loc[i,&#39;sub&#39;] = sub<br>            df.loc[i,&#39;ROI&#39;] = roi_name<br>            df.loc[i,&#39;exclusion&#39;] = 1<br>            i+=1</pre><pre>print(df)</pre><p>ผลลัพธ์ที่ได้ออกมา</p><pre>accuracy    sub    ROI exclusion<br>0  0.880000 sub-01 FFA 0.0<br>1  0.893333 sub-01 FFA 0.0<br>2  0.846667 sub-01 FFA 0.0<br>3  0.860000 sub-01 FFA 1.0<br>4  0.870000 sub-01 FFA 1.0<br>5  0.880000 sub-01 FFA 1.0<br>6  0.620000 sub-01 PPA 0.0<br>7  0.586667 sub-01 PPA 0.0<br>8  0.600000 sub-01 PPA 0.0<br>9  0.660000 sub-01 PPA 1.0<br>10 0.600000 sub-01 PPA 1.0<br>11 0.640000 sub-01 PPA 1.0<br>12 0.906667 sub-02 FFA 0.0<br>13 0.806667 sub-02 FFA 0.0<br>14 0.786667 sub-02 FFA 0.0<br>15 0.940000 sub-02 FFA 1.0<br>16 0.850000 sub-02 FFA 1.0<br>17 0.890000 sub-02 FFA 1.0<br>18 0.653333 sub-02 PPA 0.0<br>19 0.733333 sub-02 PPA 0.0<br>20 0.640000 sub-02 PPA 0.0<br>21 0.770000 sub-02 PPA 1.0<br>22 0.650000 sub-02 PPA 1.0<br>23 0.680000 sub-02 PPA 1.0<br>24 0.953333 sub-03 FFA 0.0<br>25 0.886667 sub-03 FFA 0.0<br>26 0.726667 sub-03 FFA 0.0<br>27 0.960000 sub-03 FFA 1.0<br>28 0.950000 sub-03 FFA 1.0<br>29 0.810000 sub-03 FFA 1.0<br>30 0.773333 sub-03 PPA 0.0<br>31 0.720000 sub-03 PPA 0.0<br>32 0.586667 sub-03 PPA 0.0<br>33 0.790000 sub-03 PPA 1.0<br>34 0.790000 sub-03 PPA 1.0<br>35 0.670000 sub-03 PPA 1.0</pre><p>เปรียบเทียบโดยใช้ seaborn</p><pre>sns.set_theme(style=&quot;ticks&quot;, palette=&quot;pastel&quot;)</pre><pre># Draw a nested boxplot to show bills by day and time<br>sns.boxplot(x=&quot;ROI&quot;, y=&quot;accuracy&quot;,<br>            hue=&quot;exclusion&quot;, palette=[&quot;m&quot;, &quot;g&quot;],<br>            data=df)<br>sns.despine(offset=10, trim=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2ZhIa7QHY04_TgxvxUbErg.png" /></figure><p>จะสังเกตุจากรูปดังกล่าวได้ว่า <strong>FFA </strong>มี <strong>accuracy </strong>ที่ดีกว่าอย่างเห็นได้ชัด แต่ว่าทั้งสองก็ยังแยกสัญญาณได้ดีเหมือนกัน แค่PPA decoding อาจจะมีฟังชั่นอื่นที่ทำให้ไม่ได้ดีเท่า FFA</p><h3>Special Thanks💫💫</h3><ul><li><a href="https://www.facebook.com/braincode101">https://www.facebook.com/braincode101</a></li><li>ขอขอบคุณเพื่อนๆและพี่ๆ Mentor / TA Brain code camp ที่คอยช่วยเหลือและดูแลในการเรียนรู้ของผมครั้งนี้</li><li>ผมสนุกมากๆกับ10สัปดาห์ที่ทำโปรเจกต์ กับ Brain code camp สนุกมากครับรีเสิร์ชทุกวันนั่งอ่านโค้ดแทบทุกวัน หยุมหัวตัวเองบ่อยมาก!!!!</li></ul><p>และอาจจะเป็นการแนะนำตัวที่ช้าไปหน่อย สวัสดีครับ ผมชื่อฮ๊อกกี้ กำลังศึกษาอยู่ที่โรงเรียนสาธิต มหาวิทยาลัยศรีนครินทรวิโรฒ ประสานมิตร (ฝ่ายมัธยม) ครับ<br>อยู่ชั้นมัธยมปีที่6 สถานนีต่อไปมหาวิทยาลัยจุฬาลงกรณ์ ขอบคุณครับ</p><p>ฝากติดตาม blog ตอนต่อไปของผมด้วยนะครับ!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5276f7294fac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to know percent your sound?]]></title>
            <link>https://hoggyna.medium.com/how-to-know-percent-your-sound-ff589158730e?source=rss-881fb39798e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff589158730e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <dc:creator><![CDATA[hoggyna]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 13:38:33 GMT</pubDate>
            <atom:updated>2023-06-13T14:13:23.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>เคยสงสัยกันบ้างไหมครับว่าตัวเองออกสำเนียงภาษาได้ดีมากน้อยแค่ไหนตอนฝึกพูดภาษา ถ้าคุณสงสัยแปลว่าเราเป็นพวกเดียวกัน</h4><blockquote><strong>สวัสดีครับ! โปรเจกต์นี้เป็นส่วนหนึ่งของโครงการ AI Builder 2023 เป็นการเรียนรู้ครั้งแรกในเรื่องของ AI เลยครับโปรเจกต์นี้อาจจะมีข้อผิดพลาดบ้างก็ขออภัยด้วยครับ งั้นเรามาเริ่มกันเลยดีกว่าครับ</strong></blockquote><h3>Table Of Content!</h3><p>· <a href="#4d9f">จุดเริ่มต้นของโปรเจกต์!</a><br>· <a href="#f359">ทำไมต้องโปรเจกนี้? ( Problem statement )</a><br>· <a href="#4255">Metrics and baselines</a><br>· <a href="#750e">ขั้นตอนการทำ</a><br>· <a href="#537d">Create Data(สร้างข้อมูล)</a><br>· <a href="#3bc0">Data Cleaning ( ทำความสะอาดข้อมูล )</a><br>· <a href="#f408">หลักการทำงานที่predict data</a><br>· <a href="#8161">Test non native speaker ( ทดสอบเสียงคนที่ไม่ใช่เจ้าของภาษา )</a><br>· <a href="#900d">Test native speaker ( ทดสอบเสียงคนที่เป็นเจ้าของภาษา )</a><br>· <a href="#af8b">สรุปจากการ Test Non native speaker และ Native speaker</a><br>· <a href="#6981">Finetune model </a><br>· <a href="#2adb">Deployment</a><br>· <a href="#dc37">Future!🌈🌈</a><br>· <a href="#4706">Special Thanks💫💫</a><br>· <a href="#1ed2">Link💫💫</a><br>· <a href="#a0db">Credit💫💫</a></p><h4>จุดเริ่มต้นของโปรเจกต์!</h4><p>ผมเริ่มมาจากการที่ผมนั่งคิดนอนคิดว่า จะทำโปรเจกต์อะไรดี เผอิญว่าช่วงนั้นผมมีโอกาสได้ไปเล่นกับน้อง ( น้องผมอายุเพียง2ขวบ ) แล้วน้องก็พูดไม่ซัด! เอ้ย ชัด! หลังจากนั้นผมก็มาคิดต่อยอดเกี่ยวกับการพูดที่ใกล้ๆกันมีอะไรบ้าง แล้วช่วงนั้นผมสังเกตเห็นว่าเวลาที่ผมเรียนภาษาจีนพอถึง การพูดที่เป็นประโยคสำเนียงของผมมันแปลกๆกับเจ้าของภาษาผมเลยลองไปฟังคำๆนึงของเจ้าของภาษา ทำให้ผมรู้ว่าสำเนียงของเขากับผมต่างกันอย่างมาก จึงเป็นโปรเจกต์นี้ขึ้นมาครับ</p><h4>ทำไมต้องโปรเจกนี้? ( Problem statement )</h4><p>เพราะผมคิดว่าทุกคนบนโลกนี้มีปัญหาเกี่ยวกับภาษา เป็นอย่างมากบางคนฝึกพูดภาษาแทบตายแต่ไม่รู้ว่าสำเนียงที่พูดออกมามีความเหมือนหรือคล้ายมากน้อยแค่ไหน เพราะฉะนั้นก็เลยเกิดเป็นโปรเจกนี้ขึ้นมาครับ</p><h4><strong>Metrics and baselines</strong></h4><p>ผมใช้การตรวจสอบความแม่นยำโดยใช้ recall score ,precission score และ f1 score ในการทดสอบโมเดลและทดสอบdata ทั้งหมด และ มี baselines คือ Dynamic Time Warping (DTW)</p><h3>ขั้นตอนการทำ</h3><p>ในส่วนแรกอยากให้รู้เกี่ยวกับ Dynamic Time Warping ( DTW ) เป็นเทคนิคทางคณิตศาสตร์ที่ใช้ในการวัดความคล้ายคลึงระหว่างเสียงที่มีความยาวและความเกี่ยวข้องกันแตกต่างไป หลักการทำงานของ DTW คือการหาความยาวเสียงที่เหมาะสมที่สุดในการจับคู่ซึ่งกันและกัน</p><p>หาโมเดลมาใช้งานและทดลองการทำงานของโมเดลว่าเป็นยังไงบ้าง จนมาเจอโมเดล <a href="https://huggingface.co/jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn">https://huggingface.co/jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn</a> ตัวนี้มีโค๊ดอธิบายและหลักการให้ศึกษา ผมเลยหยิบโมเดลตัวนี้มาทดสอบโมเดลว่าเป็นยังไง</p><h3>Create Data(สร้างข้อมูล)</h3><p>ในส่วนต่อมาเราต้องหาข้อมูลเพื่อมาทดสอบโมเดลว่ามีการ predict ได้ดีมากน้อยแค่ไหน โดยแบ่งข้อมูลออกมาเป็น 2 ตัว คือ <a href="https://ieee-dataport.org/open-access/latic-non-native-pre-labelled-mandarin-chinese-validation-corpus-automatic-speech#files">Non native speaker</a> และ <br><a href="https://www.aishelltech.com/aishell_3">Native speaker</a> <br>ในส่วนของข้อมูลเราโหลดไฟล์ txt เข้ามาอ่านไฟล์ด้วย pandas และ ใช้ฟั่งชั่น concat เชื่อมทุกไฟล์ txt เข้าด้วยกัน</p><pre>df = pd.read_csv(&#39;/content/latic/SCRIPT/Testing_Text_Script/0010.TXT&#39;, sep=&#39;\t&#39;, header=None, names=[&#39;id&#39;, &#39;sentence&#39;], dtype=str)<br>df2 = pd.read_csv(&#39;/content/latic/SCRIPT/Testing_Text_Script/0011.TXT&#39;, sep=&#39;\t&#39;, header=None, names=[&#39;id&#39;, &#39;sentence&#39;], dtype=str)<br>df3 = pd.read_csv(&#39;/content/latic/SCRIPT/Testing_Text_Script/0012.TXT&#39;, sep=&#39;\t&#39;, header=None, names=[&#39;id&#39;, &#39;sentence&#39;], dtype=str)<br>df4 = pd.read_csv(&#39;/content/latic/SCRIPT/Testing_Text_Script/0013.TXT&#39;, sep=&#39;\t&#39;, header=None, names=[&#39;id&#39;, &#39;sentence&#39;], dtype=str)<br>df = pd.concat([df,df2,df3,df4],ignore_index=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*imvmrDNSMewNzF-1cIYu_g.png" /><figcaption>ผลลัพธ์จากโปรแกรมข้างต้น</figcaption></figure><p>จากภาพด้านบนจะพบว่า id ยังไม่เชื่อมกับ path ของ google colab เราจึงต้องเชื่อม id ให้เข้ากับ path ของ google colab</p><pre>import os<br>import pandas as pd<br><br># Define the directory containing the .wav files and the DataFrame<br>wav_dir = &#39;/content/wav&#39;<br><br># Create a dictionary to store the file paths<br>file_dict = {}<br><br># Loop through the .wav files in the directory<br>for filename in os.listdir(wav_dir):<br>    if filename.endswith(&#39;.WAV&#39;):<br>        # Extract the id from the filename (assuming the filename is in the format &#39;id.wav&#39;)<br>        id = filename.split(&#39;.&#39;)[0]<br>        # Store the file path in the dictionary<br>        file_dict[id] = os.path.join(wav_dir, filename)<br># print(file_dict)<br># Add a new column to the DataFrame to store the file paths<br>df[&#39;path&#39;] = df[&#39;id&#39;].map(file_dict)<br><br># Print the resulting DataFrame<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*PwZ558K9LYzPdNLCW9jS9w.png" /><figcaption>ผลลัพธ์จากโปรแกรมข้างต้น</figcaption></figure><p>จากการที่เราข้อมูลเสร็จเป็นที่เรียบร้อยเราจะต้องแบ่งข้อมูลออกเป็น 3 ชนิดมีดังนี้ <br>1. test data <br>2. validation data <br>3. train data <br>และเราต้องเพิ่มในส่วนของ labels ( labels จะมี2ค่าคือ 0 และ 1 โดยที่ 1 คือเสียงพูดกับประโยคตรงกัน และ 0 คือเสียงพูดกับประโยคไม่ตรงกัน)</p><p>เราจะทำการ split training set 80% test set 10% validation set 10%</p><pre>import numpy as np<br>from sklearn.model_selection import train_test_split<br>train_df, test_df = train_test_split( df, test_size=0.8, random_state=42)<br>val_df, test_df = train_test_split( test_df, test_size=0.2, random_state=42)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*8gF8bN10R4jrerKCI60zzA.png" /><figcaption>ตัวอย่างข้อมูล</figcaption></figure><h3>Data Cleaning ( ทำความสะอาดข้อมูล )</h3><p>เราโหลดข้อมูลด้วย pandas พอเราจัดข้อมูลอยู่ในรูป csv ไว้เรียบร้อยแล้วในประโยคของไฟล์ csv จะมีพวกอักษรพิเศษ เราต้องกำจัดอักษรพิเศษทิ้งให้หมด โดยใช้ re ในการลบ ( Clean data ทั้ง Non native speaker และ Native Speaker )</p><pre>import re<br>df[&quot;sentence&quot;] = df[&quot;sentence&quot;].apply(lambda x: re.sub(&quot;[a-zA-Z\&lt;\&gt;（）“”—— !?:;./ ！ 《》：”“!，。]&quot;, &quot;&quot;, x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dKXmSfZCo1ON770-wepQ-A.png" /><figcaption>หลัง Clean Data</figcaption></figure><p>ลองสังเกตข้อมูลจากรูปของ Create Data จะมีพวกอักษรพิเศษแต่พอเรา <br>Clean Data ไปแล้วจะไม่มีอักษรพิเศษ</p><h3><strong>หลักการทำงานที่predict data</strong></h3><p>อย่างแรกคือการอ่านไฟล์เสียงโดยใช้ librosa</p><pre>import librosa<br>def speech_file_to_array_fn(path):<br><br>    speech_array, sampling_rate = librosa.load(path, sr=16_000)<br>    return speech_array</pre><p>ต่อมาคือ คลาส Realwav จะทำการโหลดโมเดล Wav2Vec2 และโปรเซสเซอร์ (processor) ที่ใช้ในการประมวลผลข้อมูลเสียง โดยในที่นี้โมเดลและโปรเซสเซอร์ที่ใช้มาจาก &quot;jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn&quot;</p><p>เมื่องคลาส Realwav ที่ใช้ฟังชั่น sound_and_sentence เพื่อประเมินคะแนนความถูกต้องของประโยคที่ออกเสียงด้วยเสียงที่พูดออกมา ( sound ) และประโยค <br>( sentence ) โดยเมธอดนี้จะทำการแปลงเสียงเป็นข้อความโดยใช้โมเดล Wav2Vec2 และ คำนวณคะแนนความถูกต้องของประโยคที่ได้ ซึ่งเมธอดจะคืนค่าคะแนนความถูกต้องของประโยค (sentence score) และคะแนนจะแปลงเป็นค่าไรบารี (0 หรือ 1) ที่บอกว่าประโยคมีความถูกต้องหรือไม่ (ถ้า predict ออกมาได้มากกว่า0.5 จะได้ค่า<br>ไรบารีเป็น 1 )</p><pre>class Realwav:<br>  def __init__(self):<br>    MODEL_ID = &quot;jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn&quot;<br>    self.processor = Wav2Vec2Processor.from_pretrained(MODEL_ID)<br>    self.model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID)<br>  <br>  def sound_and_sentence(self,sound,sentence):<br>    inputs = self.processor(sound, sampling_rate=16_000, return_tensors=&quot;pt&quot;, padding=True)<br>    with torch.no_grad():<br>        logits = self.model(inputs.input_values, attention_mask=inputs.attention_mask).logits<br>    <br>    probs = torch.softmax(logits, dim=-1)<br>    ref_ids = self.processor(text=sentence)[&quot;input_ids&quot;]<br>    scores = []<br>    ref_count = 0<br>    pred_ids = torch.argmax(logits[0], dim=-1)<br>    for seq_idx in range(pred_ids.shape[0]):<br>      if pred_ids[seq_idx] != 0:<br>        print(f&quot;position of the word {sentence[ref_count]}: {seq_idx}&quot;)<br>        ref_id = ref_ids[ref_count]<br>        conf_score = probs[0, seq_idx, ref_id].tolist()<br>        scores.append(conf_score)<br>        print(conf_score)<br>        ref_count += 1<br>        if ref_count &gt;= len(ref_ids):<br>          break<br>    sentence_score = np.mean(scores)<br>    return sentence_score, int(sentence_score &gt; 0.5)</pre><h3>Test non native speaker ( ทดสอบเสียงคนที่ไม่ใช่เจ้าของภาษา )</h3><p>เราจะสร้าง list ที่มีชื่อว่า predicts เอามาเก็บค่าที่โมเดล predict ออกมาได้</p><pre>predicts = []<br>for i in range(len(a)):<br>  sample = a.iloc[i]<br>  id = sample[&quot;id&quot;]<br>  sentence = sample[&quot;sentence&quot;]<br>  pathwav = pathtowav(id)<br>  filesound = speech_file_to_array_fn(pathwav)<br>  output = rw.sound_and_sentence(filesound,sentence)<br>  predicts.append(output[1])</pre><p>โดยผลที่ออกมาเราจะมีคะแนนทั้งหมด3แบบคือ recall score , precission score <br>และ f1 score</p><figure><img alt="ภาพด้านบนเป็นผลคะแนนที่มาจากnonNatvie" src="https://cdn-images-1.medium.com/proxy/1*NTnTnosUCHy2v913e4eUFA.png" /><figcaption>คะแนนที่ออกมาของ non native</figcaption></figure><h3>Test native speaker ( ทดสอบเสียงคนที่เป็นเจ้าของภาษา )</h3><p>เราจะสร้าง list ที่มีชื่อว่า predicts เอามาเก็บค่าที่โมเดลpredictออกมาได้</p><pre>predicts = []<br>for i in range(len(dfa)):<br>  sample = dfa.iloc[i]<br>  id = sample[&quot;UtteranceID&quot;]<br>  sentence = sample[&quot;Transcription&quot;]<br>  pathwav = pathtowav(id)<br>  filesound = speech_file_to_array_fn(pathwav)<br>  output = rw.sound_and_sentence(filesound,sentence)<br>  predicts.append(output)</pre><p>โดยผลที่ออกมาเราจะมีคะแนนทั้งหมด3แบบคือ recall score , precission score <br>และ f1 score</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uF7dli65PQ7sHi1HOscfRw.png" /><figcaption>คะแนนที่ออกมาของ native speaker</figcaption></figure><h3>สรุปจากการ Test Non native speaker และ Native speaker</h3><p>ถ้าเราดูที่คะแนนของ Native speaker จะมีคะแนนที่มากกว่า Non native speaker เป็นอย่างมาก เลยสรุปได้ดังนี้ว่าโมเดล <a href="https://huggingface.co/jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn">jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn</a> predictคนที่เป็น Non native speaker ได้ไม่ดี เราเลยต้องไป Finetune model โดยใช้ข้อมูลของคน Non native speaker เพิ่ม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*7VEXJaucqJxEoJbc0j4B8w.png" /><figcaption>สรุปคะแนนระหว่าง Non native speaker กับ Native speaker</figcaption></figure><h3>Finetune model</h3><p>Import library ที่ต้องใช้มาให้หมด</p><pre>from transformers import Wav2Vec2CTCTokenizer<br>from transformers import Wav2Vec2FeatureExtractor<br>from transformers import Wav2Vec2Processor<br>from transformers import Wav2Vec2ForCTC<br>from transformers import TrainingArguments<br>from transformers import Trainer</pre><p>เตรียม train data กับ validation data ที่อยู่ใน csv ให้พร้อม และ ไฟล์เสียงให้อยู่ใน google colab ให้พร้อม</p><p>ให้google colab เชื่อมกับ google drive</p><pre>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)</pre><p>ใช้สำหรับการดึงข้อมูลของเซ็กชันล่าสุดจากไดเรกทอรีของโมเดล (model checkpoint) ที่ระบุให้มาในรูปแบบของพาธ (path) ฟังก์ชัน get_last_checkpoint ที่นำเข้าจาก transformers.trainer_utils ใช้ในการดึงเซ็กชันล่าสุดจากไดเรกทอรีโมเดลที่กำหนดไว้</p><pre>from transformers.trainer_utils import get_last_checkpoint<br>checkpoint = get_last_checkpoint(&quot;/content/drive/MyDrive/model_checkpoints/checkpoint-1600&quot;)</pre><p>เตรียมข้อมูลในการ Finetune model</p><pre>from datasets import load_dataset, load_metric<br>common_voice_train = load_dataset(&quot;csv&quot;, data_files=[&#39;/content/train_df.csv&#39;], split=&#39;train&#39; )<br>common_voice_test = load_dataset(&quot;csv&quot;, data_files=[&#39;/content/val_df.csv&#39;], split=&#39;train&#39; )</pre><p>ตั่งค่า model เพื่อที่จะ Finetune model</p><pre>model = Wav2Vec2ForCTC.from_pretrained(<br>   &quot;facebook/wav2vec2-large-xlsr-53&quot;, <br>   attention_dropout=0.1,<br>   hidden_dropout=0.1,<br>    feat_proj_dropout=0.0,<br>   mask_time_prob=0.05,<br>   layerdrop=0.1,<br>   gradient_checkpointing=True, <br>   ctc_loss_reduction=&quot;mean&quot;, <br>   pad_token_id=processor.tokenizer.pad_token_id,<br>   vocab_size=len(processor.tokenizer)<br>)<br></pre><p>ตั้งค่า batch_size ไว้ที่8 และเทรนทั้งหมด 100 epoch</p><pre>training_args = TrainingArguments(<br>  output_dir=output_models_dir,<br>  group_by_length=True,<br>  per_device_train_batch_size=8,<br>  gradient_accumulation_steps=2,<br>  evaluation_strategy=&quot;steps&quot;,<br>  num_train_epochs=100,<br>  fp16=True,<br>  save_steps=400,<br>  eval_steps=400,<br>  logging_steps=400,<br>  learning_rate=3e-4,<br>  warmup_steps=500,<br>  save_total_limit=2,<br>)</pre><pre><br>trainer = Trainer(<br>    model=model,<br>    data_collator=data_collator,<br>    args=training_args,<br>    compute_metrics=compute_metrics,<br>    train_dataset=common_voice_train,<br>    eval_dataset=common_voice_test,<br>    tokenizer=processor.feature_extractor,<br>)</pre><p>พร้อมที่จะ Finetune model</p><pre>trainer.train(resume_from_checkpoint=checkpoint)</pre><p>ผลที่finetune ออกมา</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DU7z69JtYnBDDPpr2d8Uvg.png" /></figure><p>เอาโมเดลที่ไปfinetune ไปหาค่า recall score ,precision score <br>และf1 score ได้ผลลัพธ์ดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*s149auK80H3TJJB1.png" /><figcaption>คะแนนจากการ Finetune model</figcaption></figure><p>การ Finetune model ในครั้งนี้เกิดข้อผิดพลาดขึ้นผลคะแนนที่นำมาเทรนออกมาแย่มากๆเลยต้องกลับไปแก้ข้อมูลและทำการ Finetune model ใหม่</p><h3>Deployment</h3><p>ผม deploy ผ่าน webapp ของ streamlit เป็นที่เรียบร้อยแล้วสามารถเข้าไปเล่นหรือทดลองทดสอบเสียงตัวเองได้แล้ว <a href="https://hoggyna-ai-builder-deploymentapp-bue02s.streamlit.app/">https://hoggyna-ai-builder-deploymentapp-bue02s.streamlit.app/</a></p><p>ขั้นตอนแรก:เลือกคำที่อยากจะลองทดสอบคำภาษาจีน<br>ขั้นตอนที่สอง : คลิ๊กที่รูปไมโครโฟน พูดคำภาษาจีนที่เลือกเอาไว้(อัดเสียงเป็นเวลา2วินาที)</p><p>ใน steamlit จะมีเสียงตัวอย่างให้ฟัง และสามารถ ลองPredictเล่นได้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VcX7CJCQtqj-8Ms_UMPrg.png" /></figure><h3>Future!🌈🌈</h3><ul><li>ผมจะเรียนรู้ ฝึกฝน และพยายาม ในเรื่องAI ต่อไปเรื่อยๆ</li></ul><h3>Special Thanks💫💫</h3><ul><li><a href="https://www.facebook.com/aibuildersx/">https://www.facebook.com/aibuildersx/</a></li><li>ขอขอบคุณเพื่อนๆและพี่ๆ Mentor / TA AI Builders 2023 คอยช่วยเหลือและดูแลในการเรียนรู้ของผมครั้งนี้</li><li>ผมสนุกมากๆกับ10สัปดาห์ที่ทำai กับ AI Builder มันมากครับรีเสิร์ชทุกวันนั่งอ่านโค้ดแทบทุกวัน หยุมหัวตัวเองบ่อยมาก!!!!</li></ul><h3>Link💫💫</h3><ul><li>App : <a href="https://hoggyna-ai-builder-deploymentapp-bue02s.streamlit.app/">https://hoggyna-ai-builder-deploymentapp-bue02s.streamlit.app/</a></li><li>Github : <a href="https://github.com/hoggyna/AI-Builder">https://github.com/hoggyna/AI-Builder</a></li><li>FB : <a href="https://www.facebook.com/profile.php?id=100064466693092">https://www.facebook.com/profile.php?id=100064466693092</a></li></ul><h3>Credit💫💫</h3><ul><li>Native Speaker : <a href="https://www.aishelltech.com/aishell_3">https://www.aishelltech.com/aishell_3</a></li><li>Non Native Speaker : <a href="https://ieee-dataport.org/open-access/latic-non-native-pre-labelled-mandarin-chinese-validation-corpus-automatic-speech#files">https://ieee-dataport.org/open-access/latic-non-native-pre-labelled-mandarin-chinese-validation-corpus-automatic-speech#files</a></li><li>Model : <a href="https://huggingface.co/jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn">https://huggingface.co/jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn</a></li></ul><p>และอาจจะเป็นการแนะนำตัวที่ช้าไปหน่อย สวัสดีครับ ผมชื่อฮ๊อกกี้ กำลังศึกษาอยู่ที่โรงเรียนสาธิต มหาวิทยาลัยศรีนครินทรวิโรฒ ประสานมิตร (ฝ่ายมัธยม) ครับ <br>อยู่ชั้นมัธยมปีที่6</p><p>ฝากติดตาม blog ตอนต่อไปของผมด้วยนะครับ!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff589158730e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>