LESSON 49 OF 52 · CHAPTER 06

Coefficient Fit

User-written squared-error loss and gradient steps on small vectors

ORIGINAL SOURCE

08-coefficient-fit.srp

// Fit y = coefficient * x using an explicitly written squared-error gradient.
pure funcra loss(inputs: vector, targets: vector, coefficient: float) -> float
    needs len(inputs) > 0;
    needs len(inputs) == len(targets);
{
    return mse(scale(inputs, coefficient), targets);
}

bind inputs = [1.0, 2.0, 3.0];
bind targets = [2.0, 4.0, 6.0];
var coefficient = 0.0;
repeat 40 as iteration {
    bind residuals = add(scale(inputs, coefficient), scale(targets, -1.0));
    bind gradient = 2.0 * dot(inputs, residuals) / 3.0;
    coefficient -= 0.05 * gradient;
}
print(coefficient > 1.999999999 and coefficient < 2.000000001);
print(loss(coefficient: coefficient, targets: targets, inputs: inputs) < 1e-18);
EXPECTED OUTPUT

stdout

Verified
true
true

UNDERSTAND THE CODE

Explanation & practice

What this example teaches

User-written squared-error loss and gradient steps on small vectors

Expected behavior

true, true for coefficient and loss tolerance tests

Practice: Read the source before looking at the output. Predict the values and their order, then use the pinned compiler to execute this lesson and compare the exact fixture. Identify which operation produces the result.

हाथ से लिखा कोएफ़िशिएंट फ़िट

यह उदाहरण तीन छोटे नमूनों के लिए y = coefficient * x का गुणांक ढूँढता है। mse से त्रुटि, dot से स्पष्ट रूप से लिखा गया gradient, और repeat 40 से छोटे अपडेट होते हैं। इस प्रोग्राम में कोई automatic differentiation या सर्वसाधारण training API नहीं है।

आउटपुट: दोनों पंक्तियों में true आता है: गुणांक 2.0 के बहुत करीब है और त्रुटि तय सीमा से कम है।

अभ्यास: वह पंक्ति ढूँढें जहाँ gradient गणना होती है, और वह पंक्ति जहाँ coefficient अपडेट होता है।

Explanations are sourced from the project's English chapter guide and हिन्दी अध्याय. The Scarp program and output are unchanged.

TRY IT LOCALLY

Verify, then execute

Use the pinned compiler from the course root. Keep any imported _support files next to the source.

scarp verify examples/06-ai-foundations/08-coefficient-fit.srp scarp exec examples/06-ai-foundations/08-coefficient-fit.srp

The website does not run code. Read the CLI guide ↗

Pinned compiler: Scarp v0.0.6-alpha.3 · ceff07d9014f. No simulated output.