LESSON 49 OF 52 · CHAPTER 06
Coefficient Fit
User-written squared-error loss and gradient steps on small vectors
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);
stdout
true
true
Write what you expect this program to print. Check prediction for a line-level hint without revealing the answer, or reveal the verified output when ready. This checks displayed text only; it does not run Scarp or save your input.
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.
LEARNING PROGRESS
Keep your place
Mark this lesson complete when you are ready.
Only saved in this browser. No account or tracking.
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.srpThe website does not run code. Read the CLI guide ↗
Pinned compiler: Scarp v0.0.6-alpha.3
· ceff07d9014f. No simulated output.