Created
May 20, 2017 01:45
-
-
Save kidwai/053a9e442792cbd07929712edc150bde to your computer and use it in GitHub Desktop.
A Linear Regression Model in Solidity.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.9; | |
library Math { | |
function mul (uint a, uint b, uint decimals) internal constant returns (uint) { | |
return a*b/10**decimals; | |
} | |
function div (uint a, uint b, uint decimals) internal constant returns (uint) { | |
return a*10**decimals/b; | |
} | |
function sqr(uint a, uint decimals) internal constant returns (uint) { | |
return mul(a,a, decimals); | |
} | |
} | |
contract LinearModel { | |
event Push(address indexed from, uint x, uint y); | |
event Update(address indexed from, uint w0, uint w1); | |
uint[] public xtrain; | |
uint[] public ytrain; | |
uint[] public weights; | |
uint public decimals; | |
uint public error; | |
uint public alpha; | |
uint public iterations; | |
function LinearModel( | |
uint _decimals, | |
uint _alpha, | |
uint _iterations) | |
{ | |
alpha = _alpha; | |
decimals = _decimals; | |
iterations = _iterations; | |
weights = [10**decimals, 10**decimals]; | |
} | |
function mul (uint a, uint b) returns (uint) { | |
return Math.mul(a, b, decimals); | |
} | |
function div (uint a, uint b) returns (uint) { | |
return Math.div(a, b, decimals); | |
} | |
function update () { | |
for (var i = 0 ; i < xtrain.length; i++) { | |
weights[0] -= Math.mul(Math.mul(200,alpha, decimals), estimate(xtrain[i]) - ytrain[i], decimals); | |
weights[1] -= Math.mul(Math.mul(200, alpha, decimals), Math.mul(xtrain[i], (estimate(xtrain[i]) - ytrain[i]), decimals), decimals); | |
} | |
Update(msg.sender, weights[0], weights[1]); | |
} | |
function objective () returns (uint) { | |
error = 0; | |
for (var i = 0 ; i < xtrain.length; i++) { | |
error += Math.sqr(estimate(xtrain[i]) - ytrain[i], decimals); | |
} | |
return error; | |
} | |
function estimate(uint x) constant returns(uint) { | |
return Math.mul(weights[1],x, decimals) + weights[0]; | |
} | |
function push(uint x, uint y) { | |
xtrain.push(x); | |
ytrain.push(y); | |
Push(msg.sender,x,y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment