<?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 Waner Miranda on Medium]]></title>
        <description><![CDATA[Stories by Waner Miranda on Medium]]></description>
        <link>https://medium.com/@wanermiranda?source=rss-623b757265ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CXZlWLWVlsIML1IS61EmOg.png</url>
            <title>Stories by Waner Miranda on Medium</title>
            <link>https://medium.com/@wanermiranda?source=rss-623b757265ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:20:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wanermiranda/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[Reducing Tunning Time with Taguchi Arrays]]></title>
            <link>https://medium.com/@wanermiranda/reducing-tunning-time-with-taguchi-arrays-cee52b87cc9d?source=rss-623b757265ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/cee52b87cc9d</guid>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[model-selection]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Waner Miranda]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 23:05:58 GMT</pubDate>
            <atom:updated>2023-10-22T23:12:59.347Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>This week fooling around as always in some science channels I stumbled upon a very interesting video from NightHawkInLight, “Using Factory Optimization to Peel Eggs &amp; Improve Everything (Multivariate Experimental Design)”. It was kind of funny and I couldn’t hold myself.</p><p><a href="https://www.youtube.com/watch?v=5oULEuOoRd0&amp;t=1062s">Using Factory Optimization to Peel Eggs &amp; Improve Everything (Multivariate Experimental Design) — YouTube</a></p><p>Experimenting and measuring how much a variable can alter a result is not an easy task. Imagine you have 3 variables each with 3 values possible, to make sure you have tested all the combinations you will have to run 27 experiments. If you are a machine learning engineer each of those will be under the 5-cross-fold protocol, make the math and you will end up running 135 training jobs.</p><p>Now, back to the video, seeing him using a very a near-deterministic (many quotes) way of identifying which variable changed the easiness of pealing an Egg was not only fun but very enlightening.</p><p>We have a lot of methods to reduce the toll of training exhaustive combinations of parameters, HalvingGridSearch, Gaussian Methods and others. But nothing like that in the video where you can be sure to run a simple set of sums and know (or at least have clue) of which parameter change for good the training results.</p><p>The result was surprisingly good and with some little tweaks here and there. We can substitute those 27 experiments and 135 training jobs by 9 + 1 experiments with 50 jobs and almost the same score. That +1 I’ll explain later in the article.</p><p>As a father of a toddler, with 3 dogs, a cat and a cockatiel who got woken at 6:35 AM on a Sunday why not test it out. This is not a scientific article, but it could lead to some good insights.</p><p>Then, the saga begins:</p><h3>The Taguchi Method</h3><p>The <strong>Taguchi Method</strong>, developed by Genichi Taguchi, is a statistical method sometimes referred to as robust design methods. It was initially created to improve the quality of manufactured goods but has since been applied to various fields such as engineering, biotechnology, marketing, and advertising. The method aims to reduce variation in a process through robust design of experiments. The overall objective is to produce high-quality products at a low cost to the manufacturer.</p><p>One of the key components of the Taguchi Method is the use of <strong>orthogonal arrays</strong> in experimental design. These arrays are used to organize the parameters affecting the process and the levels at which they should be varied. Instead of having to test all possible combinations like in factorial design, the Taguchi method tests pairs of combinations. This approach allows for the collection of necessary data to determine which factors most affect product quality with a minimum amount of experimentation, thus saving time and resources.</p><p>The Taguchi method is best used when there is an intermediate number of variables (3 to 50), few interactions between variables, and when only a few variables contribute significantly. The Taguchi arrays can be derived or looked up. Small arrays can be drawn out manually; large arrays can be derived from deterministic algorithms. Analysis of variance on the collected data from the Taguchi design of experiments can be used to select new parameter values to optimize the performance characteristic.</p><p>A good example of this is the combination of 3 variables capable of 2 values each. Such as A, B, C with values L and H. In an exhaustive example we must run 8 experiments, but with Taniguchi orthogonal arrays 4 experiments is enough. To measure the impact of a score for each value of each variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*7z69KCBPvjIVvIKmh76wgA.png" /></figure><p>Then summing up the scores for each Variable Value such as:</p><pre>A = L; Score 99<br>A = H; Score 98<br>B = L; Score 89<br>B = H; Score 79<br>C = L; Score 88<br>C = H; Score 85</pre><p>The idea is that with the above calculations we can understand how impactful a change in the parameter value was. Since each value was confronted the same number of times, nullifying in that group of the other parameters.</p><p>For that example, the reduction was 2-fold, from 8 to 4. But we can have scenarios just as stated in the intro where it can be 3 times or more.</p><h3>The Implementation</h3><p>Doing some fast literature review I ended up with this article <a href="https://ieeexplore.ieee.org/document/910464/references#references">An orthogonal genetic algorithm with quantization for global numerical optimization</a>, which instead of looking at a set of fixed matrices and trying to find which fits the problem. We can build an algorithm that given a set of parameters and values we can extrapolate the orthogonal array.</p><p>For a proof of concept nothing fancy of a code based on the formulas and algorithms stated in the article mentioned above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*x-e8lsUM0v4bROcTGqhoEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*_pN7-HxhhYJMcrnBk-uiTQ.png" /></figure><pre>class Variable: <br>    _name = &quot;&quot;<br>    _values = []<br>    def __init__(self, name:str, values: list): <br>        self._name = name<br>        self._values = values<br>    def __str__(self): <br>        return f&quot;Variable(name = &#39;{self._name}&#39;, values = {self._values})&quot;<br><br>    @property<br>    def values(self) -&gt; list: <br>        return self._values<br>    <br>    @property<br>    def name(self) -&gt; str: <br>        return self._name<br>        <br>    @property<br>    def n_values(self) -&gt; int: <br>        return len(self._values)<br><br><br>class TaguchiOpt: <br>    _n_exp = 0<br>    _variables: list[Variable] = []<br>    _Q = 0<br>    _N = 0<br>    _J = 0 <br>    _M = 0 <br>    _OA = None<br>    _OA_values = None<br><br>    @classmethod<br>    def from_dict(cls, variables: dict): <br>        _vars = []<br>        for k, v in variables.items(): <br>            _vars.append(Variable(k, v))<br>        return cls(_vars)    <br>        <br>    def __init__(self, variables: list[Variable]): <br>        self._variables = variables<br>        self._N = len(variables)<br>        self.build_OA()<br><br>    def build_OA(self) -&gt; int:<br>        m_v = None <br>        for v in self._variables: <br>            if not m_v or v.n_values &gt; m_v.n_values: <br>                m_v = v <br>        self._Q = m_v.n_values<br>        self._find_J()<br>        self._M = self._Q ** self._J<br>        self._OA = np.full((self._M, self._N), 2, dtype=int)<br>        self._OA_values = np.full((self._M, self._N), None)<br>        self._fill_OA()<br>        return self<br><br>    def _fill_OA(self):<br>        ## For Basic Columns<br>        for k in range(1, self._J+1): <br>            j = int ( ((self._Q**(k-1)) - 1 ) \<br>                     / (self._Q - 1) ) + 1<br>            max_i = int(self._Q ** self._J)<br>            for i in range (1, max_i + 1): <br>                den = (self._Q ** (self._J - k))<br>                # Fixing i,j for pyhton zero based array<br>                self._OA[i-1, j-1] = int((i - 1) / den) % self._Q #if den &gt; 0 else None<br><br>        # For Non-Basic Columns<br>        for k in range (2, self._J+1): <br>            j = int ( ((self._Q ** (k-1)) - 1 ) \<br>                     / (self._Q - 1) ) + 1<br>            for s in range (1, j): <br>                for t in range (1, self._Q):<br>                    a_s = self._OA[:,s-1]<br>                    a_j = self._OA[:,j-1]<br>                    a_jj = int((j+(s-1)*(self._Q-1)+t)) - 1 <br>                    if a_jj &lt; self._N:<br>                        self._OA[:,a_jj] = np.mod(a_s *t  + a_j, self._Q)<br><br>        self._OA = self._OA[:,0:self._N]<br><br>        for i in range (0, self._M): <br>            for j in range(0, self._N): <br>                v = self._variables[j]<br>                vi  = self._OA[i,j]<br>                try: <br>                    value = v.values[vi]<br>                    self._OA_values[i, j] = value<br>                except: <br>                    print(f&quot;Error at {v}, {vi}, ({i,j})&quot;)<br>    <br>    def _calc_N_for_QJ(self): <br>        return int( (self._Q**(self._J) - 1)/(self._Q-1) )<br>        <br>    def _find_J(self): <br>        self._J = int(np.log(self._N * (self._Q-1) + 1) / np.log(self._Q))<br>        n = self._calc_N_for_QJ()<br>        if n &gt; self._N: <br>            self._J -= 1<br>        elif n &lt; self._N: <br>            self._J += 1<br>        self.N = self._calc_N_for_QJ() <br>        <br>    @property<br>    def OA(self): <br>        return self._OA_values<br><br>    def get_params(self, n=0): <br>        return { self._variables[i].name : self._OA_values[n][i] for i in range(self._N)}<br>                <br>    def __str__(self): <br>        return f&quot;(Q = {self._Q}, N  = {self._N}, J = {self._J}, M = {self._M}, N = {self._N})&quot;</pre><h3>Experiment</h3><p>I opted for some classical methods, avoiding as much interference as possible. The training set was artificially generated using scikit-learning methods with a fixed random seed, with 100 variables, 30 of which were informational and 5 thousand records. Those could lead to a quantifiable time to train and a non out of the box 100% accuracy.</p><p>The classifier was also another very commonly used model the RandomForest with non-other parameters set outside the Parameter Grid. Finally, the K-Fold protocol under cross validation with k=5, this last set to avoid testing with overfitted results.</p><pre>param_grid = {&#39;max_depth&#39;: [5, 10, 20],<br>               &#39;min_samples_split&#39;: [5, 10, 20], <br>             &#39;max_features&#39; : [&#39;sqrt&#39;, &#39;log2&#39;, None]}<br><br>base_estimator = RandomForestClassifier(random_state=42)<br><br>X, y = make_classification(n_samples=5_000, n_features=100, n_informative=30, random_state=42)<br><br>sh = GridSearchCV(base_estimator, param_grid, cv=5, verbose=2)<br>sh_fit = sh.fit(X, y)</pre><pre>TgOpt = TaguchiOpt.from_dict(param_grid)<br>results = {<br>    &#39;params&#39;: [], <br>    &#39;split0_test_score&#39;: [], <br>    &#39;split1_test_score&#39;: [],<br>    &#39;split2_test_score&#39;: [],<br>    &#39;split3_test_score&#39;: [],<br>    &#39;split4_test_score&#39;: [],<br>    &#39;mean_test_score&#39;: [], <br>    &#39;std_test_score&#39;: [],<br>    &#39;max_depth&#39;: [],<br>    &#39;min_samples_split&#39;: [], <br>    &#39;max_features&#39; : []<br>}<br><br>best_model_params = None<br>best_model_score = 0<br>for e in range(len(TgOpt.OA)): <br>    params = TgOpt.get_params(e)<br>    print(params)<br>    estimator = RandomForestClassifier(random_state=42, **params)<br>    split_scores = cross_val_score(estimator, X, y, cv=5)<br>    results[&#39;params&#39;].append(params)<br>    for k, v in params.items(): <br>        results[k].append(v)<br>    for i in range(5): <br>        results[f&#39;split{i}_test_score&#39;].append(split_scores[i])<br>    mean_score  = np.mean(split_scores)<br>    results[&#39;mean_test_score&#39;].append(mean_score) <br>    if mean_score &gt;= best_model_score: <br>        best_model_params = params<br>        best_model_score = mean_score<br>        <br>    results[&#39;std_test_score&#39;].append(np.std(split_scores))<br>    print()</pre><p>To find the best model we can build upon the experiments run using the Taguchi Arrays, sum the impacts of each parameter value and remove those values what didn’t gave us much of an improve:</p><pre>df_results_oa = pd.DataFrame(results)<br>df_results_oa.sort_values(&#39;mean_test_score&#39;, ascending=False).head(20)<br><br>for k in params.keys(): <br>    print(df_results_oa[[k, &#39;mean_test_score&#39;]].fillna(&#39;None&#39;).groupby(k).sum().reset_index().sort_values(&#39;mean_test_score&#39;, ascending=False))</pre><h3>Results and Discussion</h3><p>The overall execution and implementation were fun by itself, reading a paper that is quite common outside of my domain and bringing up that idea on things that we take as granted has a value (at least for me 😉).</p><p>As previously mentioned, this is not something that will substitute current methods of hyper parameter optimization / searching. But as Taniguchi proposed it can serve as a method to generate robust experiments with some level of explicability which is not very common in other methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*lnvIlMrkFiUn3W8hatrTpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*kBygLBPw8JGeiZiiRGh_xA.png" /><figcaption>Jobs and Time for the GridSearchCV</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*fkaHoKNRYhoHt-fcRN0BGA.png" /><figcaption>Jobs and Time for the Orthogonal Arrays</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzwDyqHgWbcphViqHk3HiQ.png" /><figcaption>Results for the GridSearchCV</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmQ8TLgZpXlYkT5D19ApZQ.png" /><figcaption>Results of the Orthogonal Arrays</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aD3rYF9NQ9KLgjINN9g6Kw.png" /><figcaption>Pruning and Fine Tunning with the Arrays + GridSearch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*VrR73kh36wgNGBMI1KWMrA.png" /><figcaption>Final Score with Arrays + GridSearch</figcaption></figure><p>We had at first a reduction of almost 3 times the number of jobs being run during the GridSearchCV against the Orthogonal Array Method, conversely the time also was a third of the exhaustive method. The score was close to the best one in the Grid Search but still some points below, but that was not final. That leaves time to spare so pruning of the current set of parameters was done based on the results of the Taniguchi method, ending up with only 2 more experiments to execute.</p><p>For a result the method yielded a score comparable to the classical method and run under a third of its time. I found that very promising and with ideas of porting it also to feature Selection and maybe even as an optimizer for an ensemble of classifiers.</p><p>I’ll leave a simple notebook over here, just in case: <a href="https://github.com/wanermiranda/taguchi_parameter_search/blob/main/Experiments.ipynb">taguchi_parameter_search/Experiments.ipynb at main · wanermiranda/taguchi_parameter_search (github.com)</a></p><p>So long and Thanks for all the Fish!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cee52b87cc9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How EDA and Spikes helped me for ML Projects estimation…]]></title>
            <link>https://medium.com/@wanermiranda/how-eda-and-spikes-helped-me-ml-projects-estimation-6d98a190b6a6?source=rss-623b757265ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d98a190b6a6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Waner Miranda]]></dc:creator>
            <pubDate>Sat, 08 Sep 2018 18:07:32 GMT</pubDate>
            <atom:updated>2018-09-08T18:10:30.217Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been working and studying with machine learning models since 2010, with weka running KNN and SVM; then Genetic Programming, RandomForests and CNN’s with my beloved python scripts. All of those scenarios matched with a big variety of datasets, from the toy ones such as IMDB, iris, and MNIST until non-curated datasets created by your clients during their life cycles of relational databases to NoSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*yYnf1H-zBiBKzzhHBH3DnA.png" /><figcaption>Regression Line vs Predicted Values.</figcaption></figure><p>“An ML project has its own mind and along with the way, measure its efforts could be a surprise…”</p><p>Every new dataset comes with the product owner telling us: “I need to predict, classify or see the data.” and then; hell breaks loose. Data scientists scream, run RandomForests or an MLP even before viewing the data and data Engineers want to remove Zeros and outliers at first glance. In that scenarios, all I saw was 1 or 2 months struggling with GridSearch on algorithms until many times the big jump in accuracy just came from a data cleaning or simply talking with the data owner (yeas the business guy, not the DBA).</p><p>“The EDA or Exploratory data analysis could be done by a set of graphs, printing the data and describing its statistics to help understand the target domain.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*lbdtylk8jkeH74mjnfD8pQ.png" /><figcaption>Columns Described using Pandas on a Toy Dataset.</figcaption></figure><p>Without knowing, I felt right to talk with the business guy who created the data. Every new chat gave an insight, a new way to view the problem. Until recently I saw myself using some sort of hidden pipeline, which doesn’t have any sophisticated name, just my guts telling me to do that every time.</p><p>1. Separate around 15% of your data into a directory you won’t see until the project ends.<br>2. Create a notebook called EDA (Exploratory Data Analysis), print your data, create graphs (there are a lot of examples on Kaggle). <br> a. One easy graph that helps a lot is the histogram for the classes (it helps you see the class distribution along the dataset. <br> b. Talk with the Product owner and ask two things: “Which that class means, which do you feel are the better columns to work with?”<br> c. After 1 day playing with the data, select a good classifier with a default configuration and less prone to overfitting such as RFs, create a simple pipeline for Train and Validation, make a run and see. <br> d. Cross-validation and grid search here is not the main concern, you want to understand the data. <br> e. With this in mind look for good metrics for your problem: <br> I. Binary Classification with (Sensitivity and Specificity with a ROC curve), don’t be fooled by accuracy metrics. <br> II. Multi-class classification with Accuracy vs Recall (I like to use Recall better than anything) <br> III. Regression — MAE, and MSE or RMSE could lead you to a wrong view, go for R2 (variability) instead firstly, it gives you a better understanding of your algorithm. <br> IV. Class Histograms, Confusion Matrix, and Regression lines are the must-have for all problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*QYxLw47o-5ysFbez68Piww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*cRizOyub8zcXswHa3ZOz6g.png" /><figcaption>Class Distribution Histograms</figcaption></figure><p>Play with it for a couple of days at least before entering the problem pipeline, understand the behavior and characteristics of your dataset.</p><p>Talk with the data Owner: Physicians, statisticians, managers, accountants, and marketers. They know the problem better you do.</p><p>Beautiful coding and a good set of dockers won’t deliver value at this point, save this for the sprint and product building.</p><p>Notebooks are for playing, use them always but don’t make them the software core.</p><p>After that Spike week, you go for the code, grab the good pieces and organize the room. Now you have a glimpse of the data, set the metrics and the model would come easier for your team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d98a190b6a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>