<?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 Almas Issakov  on Medium]]></title>
        <description><![CDATA[Stories by Almas Issakov  on Medium]]></description>
        <link>https://medium.com/@almas.issakov.t?source=rss-2b4efaabd144------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fnwa_ilG4g7whZm-_JX8dg.jpeg</url>
            <title>Stories by Almas Issakov  on Medium</title>
            <link>https://medium.com/@almas.issakov.t?source=rss-2b4efaabd144------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:14:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@almas.issakov.t/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[Linear Regression From Scratch: No libraries or frameworks]]></title>
            <link>https://medium.com/@almas.issakov.t/linear-regression-from-scratch-no-libraries-or-frameworks-9f2edb2c7397?source=rss-2b4efaabd144------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f2edb2c7397</guid>
            <dc:creator><![CDATA[Almas Issakov ]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 01:05:19 GMT</pubDate>
            <atom:updated>2026-01-16T01:18:45.032Z</atom:updated>
            <content:encoded><![CDATA[<h3>All 3 types of Regression Explained</h3><h4>no libraries and no frameworks</h4><h4>1. Simple Linear Regression on 1D:</h4><p>It used when there is only one independent variable and one dependent variable. For example: predicting house price in Almaty (independent) based on its size in m2 (dependent).</p><h4>What we want?</h4><p>We want to find our linear line: y = x * w + b</p><p>Our goal is to determine the parameters w (slope) and b (intercept) so that this line fits our data as well as possible. In other words, we want a straight line that best describes the relationship between our input variable<strong> x</strong> (size in m2) and the target values<strong> y</strong> (house price).</p><p>In simple linear regression we do <strong>not search for parameters using iterations</strong>. Instead, we derive the optimal solution analytically by minimizing the Mean Squared Error using calculus. This leads to the closed-form solution for the slope and intercept. Therefore, we obtain the best-fitting line immediately, without gradient descent or any iterative optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*EbWQhOHyuZeDGXdzxkTTMw.png" /><figcaption>closed-form formula for 1D models</figcaption></figure><p>Using the closed-form formula above calculating w and b:</p><pre>class LinearRegression1D:<br>    def __init__(self):<br>        # model parameters<br>        self.w = None<br>        self.b = None<br>        self.is_fitted = False<br><br>    def fit(self, X_train, y_train):<br>        # convert input to numpy arrays<br>        x = np.asarray(X_train)<br>        y = np.asarray(y_train)<br><br>        # compute means<br>        x_mean = np.mean(x)<br>        y_mean = np.mean(y)<br>        <br>        # compute numerator and denominator of the slope formula<br>        numerator = np.sum((x - x_mean) * (y - y_mean)) # how much x and y vary together (covariance)<br>        denominator = np.sum((x - x_mean) ** 2) # how much x varies on its own (variance)<br> <br>        self.w = numerator / denominator<br>    <br>        self.b = y_mean - self.w * x_mean<br><br>        # mark model as fitted<br>        self.is_fitted = True<br>        return self<br>    <br>    def predict(self, X_test):<br>        x = np.asarray(X_test)<br>        # linear model y = wx + b<br>        return self.w * x + self.b</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggjZ_qEnmuxHFtXZx0ZJvg.png" /></figure><h4><strong>2. Multiple Linear Regression on 2D:</strong></h4><p>Multiple linear regression handles two or more input features instead of just one. Our model going to predict the apartment price using two independent variables: the size in m2 and the distance to the city center. Each feature contributes differently to the final prediction, and the model learns one weight per feature, plus an intercept term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqQTVKNuqhRBTex-Cuy21A.png" /><figcaption>our synthetic data</figcaption></figure><p>This 3D scatter plot shows how apartment prices depend on two factors at the same time: <strong>size</strong> and <strong>distance to the city center</strong>.<br> Larger apartments and those closer to the center tend to cost more, forming an upward-sloping surface in price space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*hnNLasURARxRvawOY91TzQ.png" /><figcaption><a href="https://towardsdatascience.com/closed-form-solution-to-linear-regression-e1fe14c1cbef/">closed-form formula</a> for 2D models</figcaption></figure><p>Here is the code! No iterations are needed just using closed-from solution.</p><pre>class MulLinearRegression:<br>    def __init__(self):<br>        self.w = None        # vector of feature weights<br>        self.b = None        # intercept term (scalar)<br>        self.is_fitted = False<br>    <br>    def fit(self, X_train, y_train):<br>        X = X_train.astype(float)<br>        y = y_train.astype(float)<br><br>        # add a column of ones for the intercept term<br>        ones = np.ones((X.shape[0], 1), dtype=float)<br>        X_b = np.hstack([ones, X]) <br><br>        # compute normal equation components<br>        XtX = X_b.T @ X_b           # X^T X<br>        Xty = X_b.T @ y             # X^T y<br><br>        # closed-form solution<br>        beta = np.linalg.inv(XtX) @ Xty<br><br>        # extract intercept and weights<br>        self.b = float(beta[0])       # first element is intercept<br>        self.w = beta[1:].reshape(-1) # rest are weights<br>        self.is_fitted = True<br>        return self<br><br>    def predict(self, X):<br>        X = X.astype(float)<br>        # linear model prediction: y = Xw + b<br>        y_pred = X @ self.w + self.b<br>        return y_pred</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLy68ZcpvJDOT32X-9SWSw.png" /></figure><p>You may ask why we adding extra column of ones in code:</p><pre>ones = np.ones((X.shape[0], 1), dtype=float)<br>X_b = np.hstack([ones, X])</pre><blockquote>Answer is: to include the <strong>intercept</strong> term in the matrix formulation of linear regression, we add a column of ones to the feature matrix. This transforms each data point from [x1,x2][x_1, x_2][x1​,x2​] into [1,x1,x2][1, x_1, x_2][1,x1​,x2​], allowing the intercept b to be represented as the first element of the parameter vector. Without this column of ones, the model could only learn slopes, not the baseline offset.Limitation of the Closed-Form Solution</blockquote><h4>Limitation of the Closed-Form Solution:</h4><p>Provides an exact solution, but <strong>only for linear problems</strong>. It works because the Mean Squared Error for linear regression is a quadratic function with a single global minimum, which allows us to solve it analytically using matrix algebra. For nonlinear models or more complex loss functions, no such closed-form exists, and we must rely on iterative optimization methods like gradient descent.</p><h4>3. <strong>Polynomial Regression</strong></h4><p>Here is no closed-form! We have polynomial relation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rF2uO-rDvWsNB3fiI_pAfg.png" /><figcaption>something like this</figcaption></figure><p>Polynomial regression is still linear regression. The model remains linear in parameters, but nonlinear in inputs. The cost of this flexibility is feature explosion.</p><p>A degree-<em>d</em> polynomial with <em>n</em> features produces a combinatorial number of terms. This is where understanding <em>exactly</em> which features are generated matters, especially when you care about interpretability, overfitting, or computational cost.</p><p>To make this explicit, we’ll first build our own version of PolynomialFeatures.</p><p>First of all we need understand this:</p><pre>def _generate_combinations(self, n_features):<br>        combs = []<br>        for d in range(0, self.degree + 1):<br>            for combo in combinations_with_replacement(range(n_features), d):<br>                combs.append(combo)<br>        if not self.include_bias:<br>            combs = [c for c in combs if len(c) &gt; 0]<br>        return combs</pre><p>This function generates all polynomial feature combinations up to a given degree. It uses combinations with replacement so that features can repeat, which is necessary for terms like x² or x³. Each combination represents which input features will be multiplied together later.</p><p>When d = 0, the empty combination corresponds to the bias term. If include_bias is set to False, this term is removed. The output is a list of feature index combinations, not the final values. These combinations are used later to actually compute the polynomial features.</p><p>Secondly:</p><pre>def fit(self, X):<br>        X = np.asarray(X)<br>        n_samples, n_features = X.shape<br>        self._combination = self._generate_combinations(n_features)<br>        return self<br>    <br>    def transform(self, X):<br>        X = np.asarray(X)<br>        n_samples, n_features = X.shape<br><br>        if self._combination == None:<br>            self.fit(X)<br>        <br>        cols = []<br>        for combo in self._combination:<br>            if len(combo) == 0:<br>                col = np.ones(shape=(n_samples, ))<br>            else:<br>                col = X[:, combo[0]]<br>                for idx in combo[1:]:<br>                    col = col * X[:, idx]<br>            cols.append(col.reshape(-1, 1))<br><br>        return np.hstack(cols)<br><br>    def fit_transform(self, X):<br>        return self.fit(X).transform(X)</pre><p>The fit method determines <strong>which polynomial terms will be created</strong> based only on the number of input features. It does not modify the data itself. Instead, it stores the combinations of feature indices that define the polynomial structure.</p><p>The transform method uses these stored combinations to actually compute the polynomial features. For each combination, it multiplies the corresponding input columns. An empty combination produces a column of ones, which represents the bias term.</p><p>If transform is called before fit, the method automatically calls fit to infer the feature structure from the data.</p><p>Finally, fit_transform is a convenience method that performs both steps in one call, following the standard estimator interface used in scikit-learn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yv372OmlcB9XpXnrb-LR4A.png" /><figcaption>fitted polynomial</figcaption></figure><p><strong>How do we know which degree our polynomial should have?</strong></p><p>Increasing the polynomial degree will almost always improve the fit on training data. More parameters mean more flexibility. The problem is that this flexibility quickly turns into overfitting.</p><p><strong>Bayesian Information Criterion Formula:</strong></p><pre>def bic_score(y_true, y_pred, k):<br>    n = len(y_true)<br>    rss = np.sum((y_true - y_pred) ** 2)<br>    return n * np.log(rss / n) + k * np.log(n)</pre><p>BIC evaluates a model using two components:</p><ul><li>the error between predictions and true values</li><li>a penalty proportional to the number of model parameters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VQLcqYRsHEGWFg6UvKA6A.png" /></figure><p>The following example computes the BIC score for polynomial models of different degrees and selects the optimal one automatically.</p><blockquote>Feel free to leave a comment below and hit a like, reach me out here <a href="http://issakov.com/">issakov.com</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f2edb2c7397" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>