text
stringlengths
1
2.05k
w(65536, false)); data.append(FixedTrait::new(122501, false)); data.append(FixedTrait::new(356602, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(118987, false)); data.append(FixedTrait::new(73380, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(116781, false)); data.append(FixedTrait::new(59516, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(43895, false)); data.append(FixedTrait::new(235628, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(33706, false)); data.append(FixedTrait::new(303257, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(168385, false)); data.append(FixedTrait::new(33229, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(48750, false)); data.append(FixedTrait::new(270165, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(93906, false)); data.append(FixedTrait::new(286837, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(78782, false)); data.append(FixedTrait::new(238822, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(72450, false)); data.append(FixedTrait::new(82830, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(181409, false)); data.append(FixedTrait::new(71291, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(177934, false)); data.append(FixedTrait::new(84595, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(225287, false)); data.append(FixedTrait::new(17147, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(88127, false)); data.append(FixedTrait::new(318315, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(153231, false)); data.append(FixedTrait::new(224865, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(79552,
false)); data.append(FixedTrait::new(239072, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(21877, false)); data.append(FixedTrait::new(323515, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(75708, false)); data.append(FixedTrait::new(334208, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(68971, false)); data.append(FixedTrait::new(297859, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(97556, false)); data.append(FixedTrait::new(42705, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(109996, false)); data.append(FixedTrait::new(39914, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(28087, false)); data.append(FixedTrait::new(325975, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(12237, false)); data.append(FixedTrait::new(263902, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(90416, false)); data.append(FixedTrait::new(298075, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(115110, false)); data.append(FixedTrait::new(134701, false)); data.append(FixedTrait::new(65536, false)); let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span()); return tensor; }
use array::ArrayTrait; use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor}; use orion::numbers::{FixedTrait, FP16x16, FP16x16Impl}; fn Y_test() -> Tensor<FP16x16>{ let mut shape = ArrayTrait::new(); shape.append(50); let mut data = ArrayTrait::new();data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, fals
e)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span()); return tensor; }
use array::ArrayTrait; use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor}; use orion::numbers::{FixedTrait, FP16x16, FP16x16Impl}; fn Y_train() -> Tensor<FP16x16>{ let mut shape = ArrayTrait::new(); shape.append(100); let mut data = ArrayTrait::new();data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, t
rue)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false));
data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, false)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, true)); data.append(FixedTrait::new(65536, false)); let tensor = TensorTrait::<FP16x16>::new(shape.span(), data.span()); return tensor; }
use debug::PrintTrait; use traits::TryInto; use array::{ArrayTrait, SpanTrait}; use orion::operators::tensor::{ Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorMul, FP16x16TensorSub, FP16x16TensorDiv }; use orion::numbers::{FixedTrait, FP16x16, FP16x16Impl}; use orion::numbers::fixed_point::implementations::fp16x16::core::{ HALF, ONE, FP16x16Mul, FP16x16Div, FP16x16Print, FP16x16IntoI32, FP16x16PartialOrd, FP16x16PartialEq }; fn calculate_loss( w: @Tensor<FP16x16>, x_train: @Tensor<FP16x16>, y_train: @Tensor<FP16x16>, c: @Tensor<FP16x16>, one_tensor: @Tensor<FP16x16>, half_tensor: @Tensor<FP16x16>, y_train_len: u32 ) -> FP16x16 { let tensor_size = FixedTrait::new_unscaled(y_train_len, false); let pre_cumsum = *one_tensor - *y_train * x_train.matmul(w); let cumsum = pre_cumsum.cumsum(0, Option::None(()), Option::None(())); let sum = cumsum.data[pre_cumsum.data.len() - 1]; let mean = FP16x16Div::div(*sum, tensor_size); let mean_tensor = TensorTrait::new( shape: array![1].span(), data: array![mean].span(), ); let regularization_term = *half_tensor * (w.matmul(w)); let loss_tensor = mean_tensor + *c * regularization_term; loss_tensor.at(array![0].span()) } fn calculate_gradient( w: @Tensor<FP16x16>, x_train: @Tensor<FP16x16>, y_train: @Tensor<FP16x16>, c: Tensor<FP16x16>, one_tensor: @Tensor<FP16x16>, neg_one_tensor: @Tensor<FP16x16>, y_train_len: u32 ) -> Tensor<FP16x16> { let tensor_size = TensorTrait::new( shape: array![1].span(), data: array![FixedTrait::new_unscaled(y_train_len, false)].span(), ); let mask = (*y_train * x_train.matmul(w)); let mask = less(@mask, one_tensor); let gradient = (((mask * *y_train).matmul(x_train) / tensor_size) * *neg_one_tensor) + (c * *w); gradient } fn accuracy(y: @Tensor<FP16x16>, z: @Tensor<FP16x16>) -> FP16x16 { let (mut left, mut right) = (y, z); let mut right_data = *right.data;
let mut left_data = *left.data; let mut counter = 0; loop { match right_data.pop_front() { Option::Some(item) => { let right_current_index = item; let left_current_index = left_data.pop_front(); let (y_value, z_value) = (left_current_index.unwrap(), right_current_index); if *y_value == *z_value { counter += 1; }; }, Option::None(_) => { break; } }; }; (FixedTrait::new_unscaled(counter, false) / FixedTrait::new_unscaled((*y.data).len(), false)) * FixedTrait::new_unscaled(100, false) } fn less(y: @Tensor<FP16x16>, z: @Tensor<FP16x16>) -> Tensor<FP16x16> { let mut data_result = ArrayTrait::<FP16x16>::new(); let mut data_result2 = ArrayTrait::<FP16x16>::new(); let (mut smaller, mut bigger, retains_input_order) = if (*y.data).len() < (*z.data).len() { (y, z, true) } else { (z, y, false) }; let mut bigger_data = *bigger.data; let mut smaller_data = *smaller.data; let mut smaller_index = 0; loop { match bigger_data.pop_front() { Option::Some(item) => { let bigger_current_index = item; let smaller_current_index = smaller_data[smaller_index]; let (y_value, z_value) = if retains_input_order { (smaller_current_index, bigger_current_index) } else { (bigger_current_index, smaller_current_index) }; if *y_value < *z_value { data_result.append(FixedTrait::ONE()); } else { data_result.append(FixedTrait::ZERO()); }; smaller_index = (1 + smaller_index) % smaller_data.len(); }, Option::None(_) => { break; } }; }; return TensorTrait::<FP16x16>::new(*bigger.shap
e, data_result.span()); } fn sign(z: @Tensor<FP16x16>) -> Tensor<FP16x16> { let mut data_result = ArrayTrait::<FP16x16>::new(); let mut z_data = *z.data; loop { match z_data.pop_front() { Option::Some(item) => { let result = if *item.sign { FixedTrait::new(ONE, true) } else { FixedTrait::new(ONE, false) }; data_result.append(result); }, Option::None(_) => { break; } }; }; TensorTrait::<FP16x16>::new(*z.shape, data_result.span()) } fn pred(x: @Tensor<FP16x16>, w: @Tensor<FP16x16>) -> Tensor<FP16x16> { sign(@(x.matmul(w))) }
mod generated; mod train; mod test; mod helper;
use traits::TryInto; use array::{ArrayTrait, SpanTrait}; use orion::operators::tensor::{ Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorMul, FP16x16TensorSub, FP16x16TensorDiv }; use orion::numbers::{FixedTrait, FP16x16, FP16x16Impl}; use orion::numbers::fixed_point::implementations::fp16x16::core::{ HALF, ONE, FP16x16Mul, FP16x16Div, FP16x16IntoI32, FP16x16PartialOrd, FP16x16PartialEq }; use verifiable_support_vector_machine::{ generated::{X_train::X_train, Y_train::Y_train, X_test::X_test, Y_test::Y_test}, train::{train} }; use verifiable_support_vector_machine::{helper::{pred, accuracy}}; #[test] #[available_gas(99999999999999999)] fn svm_test() { let x_train = X_train(); let x_test = X_test(); let y_train = Y_train(); let y_test = Y_test(); let feature_size = *x_train.shape[1]; let mut zero_array = ArrayTrait::new(); let learning_rate = FixedTrait::new(655, false); // 655 is 0.01 // 50 % let average_compare = FixedTrait::new_unscaled(50, false); let mut i = 0_u32; loop { if i >= feature_size { break (); } zero_array.append(FP16x16Impl::ZERO()); i += 1; }; let initial_w = TensorTrait::new( shape: array![feature_size].span(), data: zero_array.span() ); let y_train_len = y_train.data.len(); let (final_w, initial_loss, final_loss) = train( @x_train, @y_train, @initial_w, learning_rate, y_train_len, 100_u32 ); let final_y_pred = pred(@x_test, @final_w); let average_pred = accuracy(@final_y_pred, @y_test); let train_y_pred = pred(@x_train, @final_w); let average_train = accuracy(@train_y_pred, @y_train); assert(final_loss < initial_loss, 'No decrease in training loss'); assert(average_pred > average_compare, 'It is better to flip a coin'); assert(average_train > average_compare, 'It was not a good training'); }
use debug::PrintTrait; use traits::TryInto; use array::{ArrayTrait, SpanTrait}; use orion::operators::tensor::{ Tensor, TensorTrait, FP16x16Tensor, FP16x16TensorAdd, FP16x16TensorMul, FP16x16TensorSub, FP16x16TensorDiv }; use orion::numbers::{FixedTrait, FP16x16, FP16x16Impl}; use orion::numbers::fixed_point::implementations::fp16x16::core::{ HALF, ONE, FP16x16Mul, FP16x16Div, FP16x16Print, FP16x16IntoI32, FP16x16PartialOrd, FP16x16PartialEq }; use verifiable_support_vector_machine::{helper::{calculate_loss, calculate_gradient}}; fn train_step( x: @Tensor<FP16x16>, y: @Tensor<FP16x16>, w: @Tensor<FP16x16>, learning_rate: FP16x16, one_tensor: @Tensor<FP16x16>, half_tensor: @Tensor<FP16x16>, neg_one_tensor: @Tensor<FP16x16>, y_train_len: u32, iterations: u32, index: u32 ) -> Tensor<FP16x16> { let learning_rate_tensor = TensorTrait::new( shape: array![1].span(), data: array![learning_rate].span() ); let c = TensorTrait::new( shape: array![1].span(), data: array![FP16x16Impl::ONE()].span(), ); let mut w_recursive = *w; let gradient = calculate_gradient( @w_recursive, x, y, c, one_tensor, neg_one_tensor, y_train_len ); w_recursive = w_recursive - (learning_rate_tensor * gradient); if index == iterations { return w_recursive; } train_step( x, y, @w_recursive, learning_rate, one_tensor, half_tensor, neg_one_tensor, y_train_len, iterations, index + 1 ) } fn train( x: @Tensor<FP16x16>, y: @Tensor<FP16x16>, init_w: @Tensor<FP16x16>, learning_rate: FP16x16, y_train_len: u32, iterations: u32 ) -> (Tensor<FP16x16>, FP16x16, FP16x16) { let iter_w = init_w; 'Iterations'.print(); iterations.print(); let c = TensorTrait::new( shape: array![1].span(), data: array![FP16x16Impl::ONE()].span(), ); let one_tensor = TensorTrait::new(
shape: array![1].span(), data: array![FP16x16Impl::ONE()].span(), ); let half_tensor = TensorTrait::new( shape: array![1].span(), data: array![FixedTrait::new(HALF, false)].span(), ); let neg_one_tensor = TensorTrait::new( shape: array![1].span(), data: array![FixedTrait::new(ONE, true)].span(), ); let initial_loss = FixedTrait::<FP16x16>::ZERO(); let final_loss = FixedTrait::<FP16x16>::ZERO(); let initial_loss = calculate_loss(init_w, x, y, @c, @one_tensor, @half_tensor, y_train_len); let iter_w = train_step( x, y, init_w, learning_rate, @one_tensor, @half_tensor, @neg_one_tensor, y_train_len, iterations, 1 ); let final_loss = calculate_loss(@iter_w, x, y, @c, @one_tensor, @half_tensor, y_train_len); (iter_w, initial_loss, final_loss) }
{ "cells": [ { "cell_type": "markdown", "id": "c4619365", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 1, "id": "4d401fa3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<matplotlib.collections.PathCollection at 0x7f63f2d5ca10>" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAigAAAGdCAYAAAA44ojeAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAxY0lEQVR4nO3de3SU9b3v8c8kQhJoMhpSMhMNmE3RvWPYaHCjoFVQwESNF9xapFjqhWOxupqDt0a3O8m2EC97q92lUuvyiCUi/lHB0tWFxhuUguUSYxtyaoEdBM3kxBKcSZAEmDznjzjTDJlJ5klmMs/MvF9rzVrO8/xm8ps1rfPxd/n+bIZhGAIAALCQlFh3AAAA4FQEFAAAYDkEFAAAYDkEFAAAYDkEFAAAYDkEFAAAYDkEFAAAYDkEFAAAYDmnxboDQ9HT06OWlhZlZmbKZrPFujsAACAMhmGoo6NDeXl5SkkZeIwkLgNKS0uL8vPzY90NAAAwBIcOHdJZZ501YJu4DCiZmZmSej9gVlZWjHsDAADC4fF4lJ+f7/8dH0hcBhTftE5WVhYBBQCAOBPO8gwWyQIAAMshoAAAAMshoAAAAMshoAAAAMshoAAAAMsxHVC2bNmisrIy5eXlyWazacOGDf57J06c0MMPP6wpU6Zo7NixysvL0/e+9z21tLQEvEd3d7fuu+8+5eTkaOzYsbruuuv02WefDfvDAACAxGA6oBw9elRTp07VypUr+9376quvVF9fr8cee0z19fV644039Ne "text/plain": [ "<Figure size 640x480 with 1 Axes>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "
import numpy as np\n", "
import matplotlib.pylab as plt\n", "from sklearn.metrics
import r2_score\n", "
import os\n", "\n", "N = 50\n", "noise = np.random.randn(N)+100\n", "x = np.random.randn(N)\n", "y = 8* x + noise\n", "np.random.seed(1)\n", "plt.scatter(x, y)\n", "\n" ] }, { "cell_type": "markdown", "id": "ed9e4ef7", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 2, "id": "9e4e7430", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gradient: 8.326885863832231\n", "bias: 100.05814848422345\n" ] }, { "data": { "text/plain": [ "<matplotlib.legend.Legend at 0x7f63f2d967d0>" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAigAAAGxCAYAAABIjE2TAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAABds0lEQVR4nO3deViU5cIG8HsYWRVGAWFA2SI0ETc099wXNMk1U7SDSx6PZeVxK08ZUC65Zmmaxy+1VNQ2Law0NdfjvpAimkugmBCuwyLrzPv9QTMyzDswAwMzzNy/65rrap73mXeeAXNun1UiCIIAIiIiIgtiZ+4GEBEREZXFgEJEREQWhwGFiIiILA4DChEREVkcBhQiIiKyOAwoREREZHEYUIiIiMjiMKAQERGRxWFAISIiIovDgEJkATZu3AiJRKJ51KlTB40bN8b48ePx559/1kgbAgMDMW7cOM3zgwcPQiKR4ODBg0bd59ixY4iNjcWjR49M2j4AGDduHAIDA01+X0t9XyJbxoBCZEE2bNiA48ePY+/evZg0aRK2bt2K5557Drm5uTXelvDwcBw/fhzh4eFGve7YsWOIi4urloBCRLajjrkbQERPhIWFoV27dgCAnj17QqlU4oMPPsDOnTsxZswY0dc8fvwYLi4uJm+Lm5sbOnbsaPL7EhEZgj0oRBZMHRBu3rwJoGSooV69erh48SL69esHV1dX9O7dGwBQWFiIefPm4ZlnnoGjoyMaNmyI8ePH4+7du1r3LCoqwuzZsyGXy+Hi4oKuXbvi1KlTOu+tb4jn5MmTiIyMhIeHB5ycnBAcHIxp06YBAGJjYzFr1iwAQFBQkGbIqvQ9tm/fjk6dOqFu3bqoV68e+vfvj/Pnz+u8/8aNG9G0aVM4OjqiWbNm+PLLLw36mQ0ZMgQBAQFQqVQ61zp06KDVI/Tpp5+iW7du8PLyQt26ddGiRQssXrwYRUVF5b5HamoqJBIJNm7cqHNNIpEgNjZWq+zatWuIioqCl5eX5vN8+umnWnVUKhXmzZuHpk2bwtnZGfXr10fLli3x8ccfG/S5iawNe1CILNj169cBAA0bNtSUFRYW4oUXXsDkyZPx9ttvo7i4GCqVCoMHD8aRI0cwe/ZsdO7cGTdv3kRMTAx69OiBM2fOwNnZGQAwadIkfPnll5g5cyb69u2LpKQkDBs2DNnZ2RW2Z8+ePYiMjESzZs2wfPly+
Pv7IzU1Fb/88gsA4JVXXsGDBw+wcuVKfPfdd/Dx8QEAhIaGAgAWLFiAd999F+PHj8e7776LwsJCLFmyBM899xxOnTqlqbdx40aMHz8egwcPxrJly6BQKBAbG4uCggLY2ZX/76oJEyZg8ODB+PXXX9GnTx9N+ZUrV3Dq1Cl88sknmrIbN24gKioKQUFBcHBwwG+ "text/plain": [ "<Figure size 640x480 with 1 Axes>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "numerator = sum((x - x.mean()) * (y - y.mean()))\n", "denominator = sum((x - x.mean())**2) \n", "\n", "w = numerator / denominator\n", "b = y.mean() - w * x.mean()\n", "\n", "print(\"Gradient:\", w) \n", "print(\"bias:\",b)\n", "plt.scatter(x, y)\n", "plt.title(\"Predicted values\")\n", "plt.plot(x,(w * x)+b, color='orange')\n", "plt.legend([\"Actual values\", \"Predicted value\"])" ] }, { "cell_type": "markdown", "id": "03421570", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 4, "id": "92aab9c4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "R^2 score : 0.9808663599761945\n" ] } ], "source": [ "predictions = w*x +b\n", "accuracy = r2_score(y, predictions)\n", "print(\"R^2 score :\", accuracy) " ] }, { "cell_type": "markdown", "id": "9641c98b", "metadata": {}, "source": [ " " "\n", "Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation here" ] }, { "cell_type": "code", "execution_count": 5, "id": "1e527c7f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created `linear_regression` package.\n" ] } ], "source": [ "! scarb new linear_regression" ] }, { "cell_type": "code", "execution_count": 6, "id": "5b75bcd0", "metadata": {}, "outputs": [], "source": [ "!echo -n
> linear_regression/src/lib.cairo" ] }, { "cell_type": "markdown", "id": "b84409f8", "metadata": {}, "source": [ "A new project folder will be created for you and make sure to replace the content in Scarb.toml file with the following code:\n", "```toml\n", "[package]\n", "name = \"linear_regresion\"\n", "version = \"0.1.0\"\n", "\n", "\n", "[dependencies]\n", "orion = { git = \"https: "\n", "[scripts]\n", "test = \"scarb cairo-test -f linear_regression_test\"\n", "```" ] }, { "cell_type": "code", "execution_count": 6, "id": "0bd602a0", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (3814475083.py, line 3)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn [6], line 3\u001b[0;36m\u001b[0m\n\u001b[0;31m mod test;\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ " "%%writefile linear_regression/src/lib.cairo\n", "mod test;\n", "mod data_preprocessing;\n", "mod helper_functions;\n", "mod datasets;\n", "mod model;" ] }, { "cell_type": "markdown", "id": "1d2ad43c", "metadata": {}, "source": [ "\n", " "\n", "Now, we will transition our model to cairo. We will start by converting the the x features and y labels to FP16x16 tensors numbers. " ] }, { "cell_type": "code", "execution_count": 7, "id": "e8dcc4e4", "metadata": {}, "outputs": [], "source": [ "\n", "def generate_cairo_files(data, name, folder_name):\n", " \n", " os.makedirs(f'linear_regression/src/datasets/{folder_name}', exist_ok=True)\n", " with open(os.path.join('linear_regression/src/datasets', f'{folder_name}', f\"{name}.cairo\"), \"w\") as f:\n", " f.write(\n", " \"use array::ArrayTrait;\\n\" +\n", " \"use orion::n
umbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\\n\" +\n", " \"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\n\" +\n", " \"use orion::numbers::{FP16x16, FixedTrait};\\n\\n\" +\n", " \"fn {0}() -> Tensor<FP16x16> \".format(name) + \"{\\n\" +\n", " \" let tensor = TensorTrait::<FP16x16>::new( \\n\"\n", " )\n", " \n", " if len(data.shape)>1:\n", " f.write(\" shape: array![{0},\".format(data.shape[0]))\n", " f.write(\"{0}].span(),\\n\".format(data.shape[1]))\n", " f.write(\n", " \" data: array![ \\n\"\n", " )\n", " if len(data.shape)==1:\n", " f.write(\" shape: array![{0}].span(),\\n\".format(data.shape[0]))\n", " f.write(\n", " \" data: array![ \\n\"\n", " )\n", " for val in np.nditer(data.flatten()):\n", " f.write(\" FixedTrait::new({0}, {1} ),\\n\".format(abs(int(val * 2**16)), str(val < 0).lower()))\n", " f.write(\n", " \"].span() \\n \\n\" +\n", " \");\\n\\n\"+\n", " \"return tensor; \\n\"+\n", " \"}\"\n", " )\n", " with open(os.path.join('linear_regression/src/datasets', f'{folder_name}.cairo'), 'a') as f:\n", " f.write(f\"mod {name};\\n\")" ] }, { "cell_type": "code", "execution_count": 8, "id": "130007b6", "metadata": {}, "outputs": [], "source": [ "generate_cairo_files(x, 'x_feature_data', 'linear_data')\n", "generate_cairo_files(y, 'y_label_data', 'linear_data')" ] }, { "cell_type": "code", "execution_count": 9, "id": "0e56a0d7", "metadata": {}, "outputs": [], "source": [ " "! touch linear_regressi
on/src/datasets.cairo" ] }, { "cell_type": "code", "execution_count": 10, "id": "398e349b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting linear_regression/src/datasets.cairo\n" ] } ], "source": [ "%%writefile linear_regression/src/datasets.cairo\n", "mod linear_data;" ] }, { "cell_type": "code", "execution_count": 11, "id": "753ad297", "metadata": {}, "outputs": [], "source": [ "! touch linear_regression/src/datasets/linear_data.cairo" ] }, { "cell_type": "code", "execution_count": 12, "id": "1baa1a26", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting linear_regression/src/datasets/linear_data.cairo\n" ] } ], "source": [ "%%writefile linear_regression/src/datasets/linear_data.cairo\n", "mod x_feature_data;\n", "mod y_label_data;" ] }, { "cell_type": "markdown", "id": "ce0a391b", "metadata": {}, "source": [ " "\n", "We add some helper functions that we may need during our linear regression model construction and testing" ] }, { "cell_type": "code", "execution_count": 13, "id": "e944127f", "metadata": {}, "outputs": [], "source": [ "! touch linear_regression/src/helper_functions.cairo" ] }, { "cell_type": "code", "execution_count": 14, "id": "649d0a52", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting linear_regression/src/helper_functions.cairo\n" ] } ], "source": [ "%%writefile linear_regression/src/helper_functions.cairo\n", "\n", "\n", "use debug::PrintTrait;\n", "use array::{ArrayTrait, SpanTrait};\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", "
FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "\n", " "fn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n", " let column_len = *tensor_data.shape.at(1); " " let mut result = ArrayTrait::<FP16x16>::new();\n", " " let mut i: u32 = 0;\n", " loop {\n", " if i >= column_len {\n", " break ();\n", " }\n", " result.append(tensor_data.at(indices: array![row_index, i].span()));\n", " i += 1;\n", " };\n", " let resultant_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(array![column_len].span(), data: result.span());\n", " return resultant_tensor;\n", "}\n", "\n", "\n", " "fn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n", " return tensor_transposed;\n", "}\n", "\n", "fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n", " let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n", " let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n", " let mean = *sum_result / tensor_size;\n", " return mean;\n", "}\n", "\n", " "fn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n", " let mut Y_values_ = Y_values;\n", " let mean_y_value = calculate_mean(Y_values);\n", " " let mut squared_diff_shape = array::ArrayTrait::new();\n", " squared_diff_shape.append(Y_values.data.len());\n", " let mut squared_diff_vals = array::ArrayTrait::new();\n", " let mut squared_mean_diff_shape = array::ArrayTrait::new();\n", " squared_mean_diff_shape.append
(Y_values.data.len());\n", " let mut squared_mean_diff_vals = array::ArrayTrait::new();\n", "\n", " let mut i: u32 = 0;\n", "\n", " loop {\n", " match Y_values_.data.pop_front() {\n", " Option::Some(y_value) => {\n", " let diff_pred = *y_value - *Y_pred_values.data.at(i);\n", " let squared_diff = diff_pred * diff_pred;\n", " squared_diff_vals.append(squared_diff);\n", "\n", " let diff_mean = *y_value - mean_y_value;\n", " let squared_mean_diff = diff_mean * diff_mean;\n", " squared_mean_diff_vals.append(squared_mean_diff);\n", " i += 1;\n", " },\n", " Option::None(_) => { break; }\n", " }\n", " };\n", "\n", " let squared_diff_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(squared_diff_shape.span(), squared_diff_vals.span());\n", " let squared_mean_diff_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\n", " let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_squared_mean_diff = squared_mean_diff_tensor\n", " .cumsum(0, Option::None(()), Option::None(()));\n", " let r_score = FixedTrait::new_unscaled(1, false)\n", " - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n", " / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n", "\n", " return r_score;\n", "}\n", "\n", "\n", " "fn normalize_user_x_inputs(\n", " x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut x_inputs_normalized = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let m
ut x_min = ArrayTrait::<FP16x16>::new();\n", " let mut x_max = ArrayTrait::<FP16x16>::new();\n", " let mut x_range = ArrayTrait::<FP16x16>::new();\n", " let mut result = ArrayTrait::<FP16x16>::new();\n", "\n", " if original_x_values.shape.len() > 1 {\n", " let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n", " let data_len = *transposed_tensor.shape.at(0); " " let mut i: u32 = 0;\n", " loop {\n", " if i >= data_len {\n", " break ();\n", " }\n", " let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n", " x_min.append(transposed_tensor_row.min_in_tensor());\n", " x_max.append(transposed_tensor_row.max_in_tensor());\n", " x_range\n", " .append(\n", " transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n", " );\n", " i += 1;\n", " };\n", " let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\n", " let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n", " let mut x_range_tensor = TensorTrait::new(\n", " shape: array![data_len].span(), data: x_range.span()\n", " );\n", "\n", " " if x_inputs.shape.len() > 1 {\n", " let mut j: u32 = 0;\n", " loop {\n", " if j >= *x_inputs.shape.at(0) {\n", " break ();\n", " };\n", " let mut row_data = get_tensor_data_by_row(x_inputs, j);\n", " let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n", " let mut k: u32 = 0;\n", "\n", " loop {\n", " if k >= norm
_row_data.data.len() {\n", " break ();\n", " };\n", " result.append(*norm_row_data.data.at(k));\n", " k += 1;\n", " };\n", " j += 1;\n", " };\n", " x_inputs_normalized =\n", " TensorTrait::<\n", " FP16x16\n", " >::new(\n", " array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n", " );\n", " };\n", "\n", " " if x_inputs.shape.len() == 1 {\n", " x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n", " };\n", " }\n", "\n", " if original_x_values.shape.len() == 1 {\n", " let mut x_min_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n", " let mut x_max_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\n", " let mut x_range_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(\n", " shape: array![1].span(),\n", " data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n", " .span()\n", " );\n", " let mut diff = ((x_inputs - x_min_tensor));\n", " x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n", " };\n", " return x_inputs_normalized;\n", "}\n", "\n", "\n", " "fn rescale_predictions(\n", " prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut rescale_predictions = TensorTrait::<\n", " FP16x16\n", " >::new(shape: arra
y![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let mut y_min_array = ArrayTrait::<FP16x16>::new();\n", " let mut y_max_array = ArrayTrait::<FP16x16>::new();\n", " let mut y_range_array = ArrayTrait::<FP16x16>::new();\n", "\n", " let mut y_max = y_values.max_in_tensor();\n", " let mut y_min = y_values.min_in_tensor();\n", " let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n", " " let y_min_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_min].span());\n", " let y_max_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_max].span());\n", " let y_range_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_range].span());\n", "\n", " rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n", "\n", " return rescale_predictions;\n", "}\n", "\n" ] }, { "cell_type": "markdown", "id": "079198a6", "metadata": {}, "source": [ " "\n", "We can normalize our data but for this tutorial we will not as we are working with a relitively small and simple dataset. However, it is recommended to normalize data before passing it to the linear regression model since we will be working with 16x16 fixed point numbers in cairo. This is to prevent from having overflow issues as we compute the feature gradient values (some calculations involve squaring x values which can lead to relatively large if not normalized)" ] }, { "cell_type": "code", "execution_count": 15, "id": "e2f82c96", "metadata": {}, "outputs": [], "source": [ "! touch linear_regression/src/data_preprocessing.cairo" ] }, { "cell_type": "code", "execution_count": 16, "id": "089f888f", "metadata": {}, "outputs": [ { "name": "stdout", "outp
ut_type": "stream", "text": [ "Overwriting linear_regression/src/data_preprocessing.cairo\n" ] } ], "source": [ "\n", "%%writefile linear_regression/src/data_preprocessing.cairo\n", "\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "use linear_regresion::helper_functions::{\n", " get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n", " normalize_user_x_inputs, rescale_predictions\n", "};\n", "\n", " "
struct Dataset {\n", " x_values: Tensor<FP16x16>,\n", " y_values: Tensor<FP16x16>,\n", "}\n", "\n", " "impl DataPreprocessing of DatasetTrait {\n", " fn normalize_dataset(ref self: Dataset) -> Dataset {\n", " let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n", " let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n", " " if self.x_values.shape.len() > 1 {\n", " x_values = normalize_feature_data(self.x_values);\n", " y_values = normalize_label_data(self.y_values);\n", " }\n", " " if self.x_values.shape.len() == 1 {\n", " x_values = normalize_label_data(self.x_values);\n", " y_values = normalize_label_data(self.y_values);\n", " }\n", "\n", " return Dataset { x_values, y_values };\n", " }\n", "}\n", "\n", " "fn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let mut x_min_array = ArrayTrait::<FP16x16>::new();\n", " let mut x_max_array = ArrayTrait::<FP16x16>::new();\n", " let mut x_range_array = ArrayTrait::<FP16x16>::new();\n", " let mut normalized_array = ArrayTrait::<FP16x16>::new();\n", " " let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\n", " let tensor_shape = transposed_tensor.shape;\n", " let tensor_row_len = *tensor_shape.at(0); " let tensor_column_len = *tensor_shape.at(1); " " let mut i: u32 = 0;\n", " loop {\n", " if i >= tensor_row_len {\n", " break ();\n", " }\n", " let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n", " x_max_array.append(transposed_tensor_row.max_in_tensor());\n", " x_min_array.append(transposed_tensor_row.min
_in_tensor());\n", " x_range_array\n", " .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\n", " i += 1;\n", " };\n", " " let mut x_min = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\n", " let mut x_range = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\n", " let normalized_tensor = (tensor_data - x_min) / x_range;\n", " return normalized_tensor;\n", "}\n", "\n", " "fn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let mut tensor_data_ = tensor_data;\n", " let mut normalized_array = ArrayTrait::<FP16x16>::new();\n", " let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\n", " " let mut i: u32 = 0;\n", "\n", " loop {\n", " match tensor_data_.data.pop_front() {\n", " Option::Some(tensor_val) => {\n", " let mut diff = *tensor_val - tensor_data.min_in_tensor();\n", " normalized_array.append(diff / range);\n", " i += 1;\n", " },\n", " Option::None(_) => { break; }\n", " };\n", " };\n", " " let mut normalized_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\n", " return normalized_tensor;\n", "}\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "d2c1d5bf", "metadata": {}, "source": [ " "\n", "Implement the Linear Regression functions" ] }, { "cell_type": "code", "execution_count": 17, "id": "ba6e1b1a", "metadata": {}, "outputs": [], "source": [ "os.makedirs(f'linear_regression/src/model/', exist_ok=True)"
] }, { "cell_type": "code", "execution_count": 18, "id": "f310112c", "metadata": {}, "outputs": [], "source": [ "! touch linear_regression/src/model/linear_regression_model.cairo" ] }, { "cell_type": "code", "execution_count": 19, "id": "7703f49a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting linear_regression/src/model/linear_regression_model.cairo\n" ] } ], "source": [ "%%writefile linear_regression/src/model/linear_regression_model.cairo\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "use linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\n", "use linear_regresion::helper_functions::{\n", " get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n", " normalize_user_x_inputs, rescale_predictions\n", "};\n", "\n", " "
struct LinearRegressionModel {\n", " gradient: Tensor<FP16x16>,\n", " bias: Tensor<FP16x16>\n", "}\n", "\n", " "impl RegressionOperation of LinearRegressionModelTrait {\n", " fn predict(ref self: LinearRegressionModel, x_input: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let gradient = self.gradient;\n", " let bias = self.bias;\n", " let mut prediction = (gradient * x_input) + bias;\n", " return prediction;\n", " }\n", "}\n", "\n", "fn LinearRegression(dataset: Dataset) -> LinearRegressionModel {\n", " let gradient = compute_gradient(dataset);\n", " let bias = compute_bias(dataset);\n", " return LinearRegressionModel { gradient, bias };\n", "}\n", "\n", " "fn compute_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n", " let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n", " let mean = *sum_result / tensor_size;\n", " let mut result_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![mean].span());\n", " return result_tensor;\n", "}\n", "\n", "\n", " "fn deviation_from_mean(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let mut tensor_data_ = tensor_data;\n", " let mean_value = calculate_mean(tensor_data);\n", " let mut tensor_shape = array::ArrayTrait::new();\n", " tensor_shape.append(tensor_data.data.len());\n", " let mut deviation_values = array::ArrayTrait::new();\n", "\n", " let mut i: u32 = 0;\n", "\n", " loop {\n", " match tensor_data_.data.pop_front() {\n", " Option::Some(tensor_val) => {\n", " let distance_from_mean = *tensor_val - mean_value;\n",
" deviation_values.append(distance_from_mean);\n", " i += 1;\n", " },\n", " Option::None(_) => { break; }\n", " };\n", " };\n", " let distance_from_mean_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(tensor_shape.span(), deviation_values.span());\n", "\n", " return distance_from_mean_tensor;\n", "}\n", "\n", " "fn compute_gradient(dataset: Dataset) -> Tensor<FP16x16> {\n", " let x_deviation = deviation_from_mean(dataset.x_values);\n", " let y_deviation = deviation_from_mean(dataset.y_values);\n", "\n", " let x_y_covariance = x_deviation.matmul(@y_deviation);\n", " let x_variance = x_deviation.matmul(@x_deviation);\n", "\n", " let beta_value = x_y_covariance / x_variance;\n", "\n", " return beta_value;\n", "}\n", "\n", "\n", " "fn compute_bias(dataset: Dataset) -> Tensor<FP16x16> {\n", " let x_mean = compute_mean(dataset.x_values);\n", " let y_mean = compute_mean(dataset.y_values);\n", " let gradient = compute_gradient(dataset);\n", " let mx = gradient * x_mean;\n", " let intercept = y_mean - mx;\n", " return intercept;\n", "}\n", "\n" ] }, { "cell_type": "code", "execution_count": 20, "id": "8be0b0e6", "metadata": {}, "outputs": [], "source": [ "! touch linear_regression/src/model.cairo" ] }, { "cell_type": "code", "execution_count": 21, "id": "4fecca6e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting linear_regression/src/model.cairo\n" ] } ], "source": [ "%%writefile linear_regression/src/model.cairo\n", "mod linear_regression_model;" ] }, { "cell_type": "markdown", "id": "e9321f85", "metadata": {}, "source": [ " "\n", "Running some checks to ensure the model is performing a
s expected. Some of the checks involve:\n", "- tensor shape/dimension check\n", "- gradient and bias value and dimension checks \n", "- model accuracy deviance checks" ] }, { "cell_type": "code", "execution_count": 22, "id": "f32a96db", "metadata": {}, "outputs": [], "source": [ "! touch linear_regression/src/test.cairo" ] }, { "cell_type": "code", "execution_count": 23, "id": "619cff0f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting linear_regression/src/test.cairo\n" ] } ], "source": [ "%%writefile linear_regression/src/test.cairo\n", " "use debug::PrintTrait;\n", "use array::{ArrayTrait, SpanTrait};\n", "\n", "\n", "use linear_regresion::datasets::linear_data::x_feature_data::x_feature_data;\n", "use linear_regresion::datasets::linear_data::y_label_data::y_label_data;\n", "\n", "\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "use linear_regresion::model::linear_regression_model::{\n", " LinearRegressionModel, compute_mean, LinearRegression, LinearRegressionModelTrait\n", "};\n", "\n", "use linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\n", "use linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \n", "calculate_r_score, normalize_user_x_inputs, rescale_predictions};\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \n", " FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\n", "\n", " " "
fn multiple_linear_regression_test() {\n", "\n", "\n", " "\n", "let mut main_x_vals = x_feature_data();\n", "let mut main_y_vals = y_label_data();\n", "let dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\n", "let mut model = LinearRegression(dataset);\n", "let gradient = model.gradient;\n", "let mut reconstructed_ys = model.predict(main_x_vals);\n", "let mut r_squared_score = calculate_r_score(main_y_vals,reconstructed_ys);\n", "r_squared_score.print(); \n", "\n", " "assert(model.gradient.data.len() == 1, 'gradient data shape mismatch');\n", "assert(model.bias.data.len() == 1, 'bias data shape mismatch');\n", " "assert(r_squared_score >= FixedTrait::new(62259, false), 'Linear model acc. less than 95%');\n", "\n", "\n", " "let mut user_value = TensorTrait::<FP16x16>::new(shape: array![2].span(), data: array![FixedTrait::new(65536, false), FixedTrait::new(65536, true)].span());\n", "let mut prediction_results = model.predict(user_value);\n", "(*prediction_results.data.at(0)).print(); \n", "(*prediction_results.data.at(1)).print();\n", "\n", "\n", "}\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a3ac443e", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.4" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "cell_type": "markdown", "id": "97bdc270", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 1, "id": "ae4ed5fb", "metadata": {}, "outputs": [], "source": [ "
import numpy as np\n", "
import pandas as pd\n", "
import matplotlib.pyplot as plt\n", "
import pandas as pd\n", "
import os\n", "from sklearn.metrics
import r2_score" ] }, { "cell_type": "code", "execution_count": 2, "id": "4768aa34", "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>CRIM</th>\n", " <th>ZN</th>\n", " <th>INDUS</th>\n", " <th>CHAS</th>\n", " <th>NOX</th>\n", " <th>RM</th>\n", " <th>AGE</th>\n", " <th>DIS</th>\n", " <th>RAD</th>\n", " <th>TAX</th>\n", " <th>PTRATIO</th>\n", " <th>MEDV</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>0.40771</td>\n", " <td>0.0</td>\n", " <td>6.20</td>\n", " <td>1</td>\n", " <td>0.507</td>\n", " <td>6.164</td>\n", " <td>91.3</td>\n", " <td>3.0480</td>\n", " <td>8</td>\n", " <td>307</td>\n", " <td>17.4</td>\n", " <td>21.7</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>0.26838</td>\n", " <td>0.0</td>\n", " <td>9.69</td>\n", " <td>0</td>\n", " <td>0.585</td>\n", " <td>5.794</td>\n", " <td>70.6</td>\n", " <td>2.8927</td>\n", " <td>6</td>\n", " <td>391</td>\n", " <td>1
9.2</td>\n", " <td>18.3</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>0.05360</td>\n", " <td>21.0</td>\n", " <td>5.64</td>\n", " <td>0</td>\n", " <td>0.439</td>\n", " <td>6.511</td>\n", " <td>21.1</td>\n", " <td>6.8147</td>\n", " <td>4</td>\n", " <td>243</td>\n", " <td>16.8</td>\n", " <td>25.0</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>11.16040</td>\n", " <td>0.0</td>\n", " <td>18.10</td>\n", " <td>0</td>\n", " <td>0.740</td>\n", " <td>6.629</td>\n", " <td>94.6</td>\n", " <td>2.1247</td>\n", " <td>24</td>\n", " <td>666</td>\n", " <td>20.2</td>\n", " <td>13.4</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>2.31390</td>\n", " <td>0.0</td>\n", " <td>19.58</td>\n", " <td>0</td>\n", " <td>0.605</td>\n", " <td>5.880</td>\n", " <td>97.3</td>\n", " <td>2.3887</td>\n", " <td>5</td>\n", " <td>403</td>\n", " <td>14.7</td>\n", " <td>19.1</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PTRATIO \\\n", "0 0.40771 0.0 6.20 1 0.507 6.164 91.3 3.0480 8 307 17.4 \n", "1 0.26838 0.0 9.69 0 0.585 5.794 70.6 2.8927 6 391 19.2 \n", "2 0.05360 21.0 5.64 0 0.439 6.511 21.1 6.8147 4 243 16.8 \n", "3 11.16040 0.0 18.10 0 0.740 6.629 94.6 2.1247 24 666 20.2 \n", "4 2.31390 0.0 19.58 0 0.605 5.880
97.3 2.3887 5 403 14.7 \n", "\n", " MEDV \n", "0 21.7 \n", "1 18.3 \n", "2 25.0 \n", "3 13.4 \n", "4 19.1 " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_csv(\"boston_dataset.csv\")\n", "df.drop('Unnamed: 0', axis=1, inplace=True)\n", "\n", "df.head()\n", "\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "c88f769e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(50, 12)\n" ] } ], "source": [ "print(df.shape)" ] }, { "cell_type": "markdown", "id": "66a093ca", "metadata": {}, "source": [ " "• CRIM per capita crime rate by town <br>\n", "• ZN proportion of residential land zoned for lots over 25,000 sq.ft. <br>\n", "• INDUS proportion of non-retail business acres per town <br>\n", "• CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)<br>\n", "• NOX nitric oxides concentration (parts per 10 million) <br>\n", "• RM average number of rooms per dwelling <br>\n", "• AGE proportion of owner-occupied units built prior to 1940 <br>\n", "• DIS weighted distances to five Boston employment centres <br>\n", "• RAD index of accessibility to radial highways <br>\n", "• TAX full-value property-tax rate per 10,000 dollars <br>\n", "• PTRATIO pupil-teacher ratio by town <br>\n", "• MEDV Median value of owner-occupied homes in $1000's <br>\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "a3d9d8b1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(50, 11)\n", "(50,)\n" ] } ], "source": [ "features = df.drop(['MEDV',], axis=1)\n", "target = df['MEDV']\n", "\n", " "X_original = features.to_numpy()\n", "Y_or
iginal = target.to_numpy()\n", "\n", "print(X_original.shape)\n", "print(Y_original.shape)" ] }, { "cell_type": "markdown", "id": "fc086887", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 5, "id": "587dcfb9", "metadata": {}, "outputs": [], "source": [ " "\n", "def normalize_data(original_data):\n", " data_min = np.min(original_data, axis=0)\n", " data_max = np.max(original_data, axis=0)\n", " data_range = data_max - data_min\n", " data_normalized = (original_data - data_min) / data_range\n", " \n", " return data_normalized" ] }, { "cell_type": "code", "execution_count": 6, "id": "fd6c797f", "metadata": {}, "outputs": [], "source": [ "X_normalized= normalize_data(X_original)\n", "y_normalized= normalize_data(Y_original)" ] }, { "cell_type": "markdown", "id": "e2bddf32", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 7, "id": "c1fb0d79", "metadata": {}, "outputs": [], "source": [ "def transpose_and_add_bias(feature_data):\n", " " transposed_data= feature_data.T\n", " " transposed_data_with_bias = np.vstack((transposed_data, np.ones(transposed_data.shape[1])))\n", " \n", " return transposed_data_with_bias" ] }, { "cell_type": "code", "execution_count": 8, "id": "feeab27f", "metadata": {}, "outputs": [], "source": [ "def decorrelate_features(feature_data):\n", "\n", " " x_temp = feature_data.copy()\n", " \n", " " feature_rows = feature_data.shape[0]\n", " \n", " " for i in range(feature_rows):\n", " feature_squared = np.sum(x_temp[i]**2)\n", " for j in range(i+1, feature_rows):\n", " feature_cross_prod = np.sum(x_temp[i] * x_temp[j])\n", " if feature_squared == 0:\n", "
print('Warning, division by zero encountered and handled')\n", " feature_squared = 1e-8 \n", " feature_grad = feature_cross_prod / feature_squared\n", " x_temp[j] -= feature_grad * x_temp[i]\n", " \n", " decorelated_x_vals = x_temp\n", "\n", " return decorelated_x_vals\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "617f3d11", "metadata": {}, "outputs": [], "source": [ "def calculate_gradients(decorelated_x_vals, y_values, original_x_features):\n", " \n", " " feature_rows = decorelated_x_vals.shape[0]\n", " gradients = np.zeros(feature_rows)\n", "\n", " " for i in range(feature_rows-1, -1, -1):\n", " prod = np.sum(y_values * decorelated_x_vals[i])\n", " squared = np.sum(decorelated_x_vals[i] * decorelated_x_vals[i])\n", " if squared == 0:\n", " print('Warning, division by zero encountered and handled')\n", " squared = 1e-8\n", "\n", " gradients[i] = prod / squared\n", " y_values -= gradients[i] * original_x_features[i]\n", " \n", "\n", " return gradients" ] }, { "cell_type": "code", "execution_count": 10, "id": "f07ae5a1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training data shapes:\n", "X_normalized: (12, 50)\n", "y_normalized: (50,)\n" ] } ], "source": [ "X_normalized_transposed_with_bias = transpose_and_add_bias(X_normalized)\n", "\n", "print(\"Training data shapes:\")\n", "print(\"X_normalized:\", X_normalized_transposed_with_bias.shape)\n", "print(\"y_normalized:\", y_normalized.shape)" ] }, { "cell_type": "code", "execution_count": 11, "id": "e3a13196", "metadata": {}, "outputs": [], "source": [ "decorrelate_X_features = decorrelate_features(X_normalized_tra
nsposed_with_bias)" ] }, { "cell_type": "code", "execution_count": 12, "id": "21864d6b", "metadata": {}, "outputs": [], "source": [ "decorrelate_X_features = decorrelate_features(X_normalized_transposed_with_bias)" ] }, { "cell_type": "code", "execution_count": 13, "id": "8090dcd8", "metadata": {}, "outputs": [], "source": [ "gradient_values = calculate_gradients(decorrelate_X_features, y_normalized, X_normalized_transposed_with_bias )" ] }, { "cell_type": "code", "execution_count": 14, "id": "11b052e5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([ 0.43365324, -0.18175555, -0.42523263, 0.13711559, -0.19621044,\n", " -0.06995875, 0.62886834, -0.08972977, -0.0081258 , 0.00121573,\n", " 0.0482544 , 0.13295955])" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "real_gradient_values_reversed = np.flip(gradient_values)\n", "real_gradient_values_reversed" ] }, { "cell_type": "code", "execution_count": 15, "id": "b27055f3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([ 0.13295955, 0.0482544 , 0.00121573, -0.0081258 , -0.08972977,\n", " 0.62886834, -0.06995875, -0.19621044, 0.13711559, -0.42523263,\n", " -0.18175555, 0.43365324])" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gradient_values" ] }, { "cell_type": "markdown", "id": "4f970ffa", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 16, "id": "7dab4a56", "metadata": {}, "outputs": [], "source": [ "def denormalize_data(original_data,normalized_data):\n", " \n", " data_min = np.min(original_data)\n", " data_max = np.max(original_data)\n", " da
ta_range = data_max - data_min\n", " \n", " denormalize_data = ( normalized_data * data_range) + data_min\n", " return denormalize_data" ] }, { "cell_type": "code", "execution_count": 17, "id": "f3a73a20", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "R^2 score (denormalized): 0.8497719822024984\n" ] }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAh8AAAGxCAYAAADCo9TSAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAADa9UlEQVR4nOydd5gb5bn27xl1aYu2F++6d1ww2BRTbIoxGAjEIRC6aSEQCA7hw8cQgiEJLcCBHE5yUsAGQk0IKfRqQ2g27r2u6/a+qzaSZr4/3vcdjbTqq7p+f9e11+6ORtJII83c85T7ERRFUcDhcDgcDoeTIcRsbwCHw+FwOJyjCy4+OBwOh8PhZBQuPjgcDofD4WQULj44HA6Hw+FkFC4+OBwOh8PhZBQuPjgcDofD4WQULj44HA6Hw+FkFC4+OBwOh8PhZBQuPjgcDofD4WQULj44Q5oVK1ZAEAT1x2w2o7q6GmeccQYefvhhtLa2ZnsTc45ly5ZBEISgZXPnzsXcuXMzvi2CIGDZsmVR19m/f3/QPhZFEWVlZViwYAG++uqrjGznokWLMHLkyKBl8Wx7KI2NjVi2bBk2bNgw4LZw+4XDyVf02d4ADicTLF++HBMnToTX60Vrayv+85 "text/plain": [ "<Figure size 640x480 with 1 Axes>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "y_pred_norm = gradient_values @ X_normalized_transposed_with_bias "\n", "reconstructed_y = denormalize_data(Y_original,y_pred_norm)\n", "\n", " "plt.figure(2)\n", "plt.title(\"Denormalized Prediction\")\n", "plt.plot(Y_original)\n", "plt.plot(reconstructed_y)\n", "plt.legend([\"original y values\", \"reconstructed ys\"])\n", "\n", " "accuracy_denormalized = r2_score(Y_original, reconstructed_y)\n", "print(\"R^2 score (denormalized):\", accuracy_denormalized)" ] }, { "cell_type": "markdown", "id": "302d8725", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 18, "id": "2bfac80e", "metadata": {}, "outputs": [ { "data": { "text/plain": [
"array([ 0.40771, 0. , 6.2 , 1. , 0.507 , 6.164 ,\n", " 91.3 , 3.048 , 8. , 307. , 17.4 ])" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ " "X_original[0] ] }, { "cell_type": "code", "execution_count": 19, "id": "2fbe2acc", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.3628772191870112\n" ] } ], "source": [ " " " "\n", "user_input_feature_values = X_original[0]\n", "\n", "X_min = np.min(X_original, axis=0)\n", "X_max = np.max(X_original, axis=0)\n", "X_range = X_max - X_min\n", " "normalized_vals = (user_input_feature_values - X_min) / X_range\n", " "user_input_feature_values_normalized_with_bias = np.append(normalized_vals, 1)\n", "\n", " "prediction_normalized = gradient_values @ user_input_feature_values_normalized_with_bias\n", "print(prediction_normalized)" ] }, { "cell_type": "code", "execution_count": 20, "id": "535f23d1", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "24.32395193323655" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ " "Y_min = np.min(Y_original, axis=0)\n", "Y_max = np.max(Y_original, axis=0)\n", "Y_range = Y_max - Y_min\n", " "denormlized_house_value_estimation = (prediction_normalized * Y_range) + Y_min\n", "denormlized_house_value_estimation" ] }, { "cell_type": "markdown", "id": "ea617854", "metadata": {}, "source": [ " " "\n", "Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation here" ] }, { "cell_type": "code", "execution_cou
nt": 21, "id": "35d4e483", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created `multiple_linear_regression` package.\n" ] } ], "source": [ "! scarb new multiple_linear_regression" ] }, { "cell_type": "code", "execution_count": 22, "id": "e4211294", "metadata": {}, "outputs": [], "source": [ "! echo -n > multiple_linear_regression/src/lib.cairo" ] }, { "cell_type": "markdown", "id": "72afd4c8", "metadata": {}, "source": [ "A new project folder will be created for you and make sure to replace the content in Scarb.toml file with the following code:\n", "```toml\n", "[package]\n", "name = \"multiple_linear_regresion\"\n", "version = \"0.1.0\"\n", "\n", "\n", "[dependencies]\n", "orion = { git = \"https: "\n", "[scripts]\n", "test = \"scarb cairo-test -f multiple_linear_regression_test\"\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "2aab745d", "metadata": {}, "outputs": [], "source": [ " "%%writefile -a multiple_linear_regression/src/lib.cairo\n", "mod test;\n", "mod data_preprocessing;\n", "mod helper_functions;\n", "mod datasets;\n", "mod model;" ] }, { "cell_type": "markdown", "id": "2ecade3b", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 23, "id": "4192fdf0", "metadata": {}, "outputs": [], "source": [ " "\n", "\n", "def generate_cairo_files(data, name, folder_name):\n", " \n", " os.makedirs(f'multiple_linear_regression/src/datasets/{folder_name}', exist_ok=True)\n", " with open(os.path.join('multiple_linear_regression/src/datasets', f'{folder_name}', f\"{name}.cairo\"), \"w\") as f:\n", " f.write(\n", " \"use array::ArrayTrait;\\n\" +\n", " \"use orion::numbers::fixed_point::implem
entations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\\n\" +\n", " \"use orion::operators::tensor::{Tensor, TensorTrait, FP16x16Tensor};\\n\" +\n", " \"use orion::numbers::{FP16x16, FixedTrait};\\n\\n\" +\n", " \"fn {0}() -> Tensor<FP16x16> \".format(name) + \"{\\n\" +\n", " \" let tensor = TensorTrait::<FP16x16>::new( \\n\"\n", " )\n", " \n", " if len(data.shape)>1:\n", " f.write(\" shape: array![{0},\".format(data.shape[0]))\n", " f.write(\"{0}].span(),\\n\".format(data.shape[1]))\n", " f.write(\n", " \" data: array![ \\n\"\n", " )\n", " if len(data.shape)==1:\n", " f.write(\" shape: array![{0}].span(),\\n\".format(data.shape[0]))\n", " f.write(\n", " \" data: array![ \\n\"\n", " )\n", " for val in np.nditer(data.flatten()):\n", " f.write(\" FixedTrait::new({0}, {1} ),\\n\".format(abs(int(val * 2**16)), str(val < 0).lower()))\n", " f.write(\n", " \"].span() \\n \\n\" +\n", " \");\\n\\n\"+\n", " \"return tensor; \\n\"+\n", " \"}\"\n", " )\n", " with open(os.path.join('multiple_linear_regression/src/datasets', f'{folder_name}.cairo'), 'a') as f:\n", " f.write(f\"mod {name};\\n\")" ] }, { "cell_type": "code", "execution_count": 24, "id": "b05daac1", "metadata": {}, "outputs": [], "source": [ "generate_cairo_files(X_original, 'boston_x_features', 'boston_data')\n", "generate_cairo_files(Y_original, 'boston_y_labels', 'boston_data') " ] }, { "cell_type": "code", "execution_count": 25, "id": "30fe7dca", "metadata": {}, "outputs": [], "source": [ "generate_cairo_files
(user_input_feature_values, 'user_inputs_boston_data', 'user_inputs_data')" ] }, { "cell_type": "code", "execution_count": 26, "id": "02e8a2d0", "metadata": {}, "outputs": [], "source": [ " "! touch multiple_linear_regression/src/datasets.cairo" ] }, { "cell_type": "code", "execution_count": 27, "id": "f8cdb5fa", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/datasets.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression/src/datasets.cairo\n", "mod boston_data;\n", "mod user_inputs_data;" ] }, { "cell_type": "code", "execution_count": 28, "id": "cd1ca29f", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/datasets/boston_data.cairo" ] }, { "cell_type": "code", "execution_count": 29, "id": "4350c425", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/datasets/boston_data.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression/src/datasets/boston_data.cairo\n", "mod boston_x_features;\n", "mod boston_y_labels;" ] }, { "cell_type": "code", "execution_count": 30, "id": "f034a5e0", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/datasets/user_inputs_data.cairo" ] }, { "cell_type": "code", "execution_count": 31, "id": "d3235299", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/datasets/user_inputs_data.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression/src/datasets/user_inputs_data.cairo\n", "mod user_inputs_boston_data;" ] }, { "cell_type": "markdown", "id":
"ea3dd5d9", "metadata": {}, "source": [ " "\n", "We add some helper functions to make it easier to construct our MLR model" ] }, { "cell_type": "code", "execution_count": 32, "id": "24ae59be", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/helper_functions.cairo" ] }, { "cell_type": "code", "execution_count": 33, "id": "a51190ec", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/helper_functions.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression/src/helper_functions.cairo\n", "\n", "use debug::PrintTrait;\n", "use array::{ArrayTrait, SpanTrait};\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "\n", " "fn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n", " let column_len = *tensor_data.shape.at(1); " " let mut result = ArrayTrait::<FP16x16>::new();\n", " " let mut i: u32 = 0;\n", " loop {\n", " if i >= column_len {\n", " break ();\n", " }\n", " result.append(tensor_data.at(indices: array![row_index, i].span()));\n", " i += 1;\n", " };\n", " let resultant_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(array![column_len].span(), data: result.span());\n", " return resultant_tensor;\n", "}\n", "\n", "\n", " "fn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n", " return tensor_transposed;\n", "}\n", "
\n", "fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n", " let tensor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n", " let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n", " let mean = *sum_result / tensor_size;\n", " return mean;\n", "}\n", "\n", " "fn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n", " let mut Y_values_ = Y_values;\n", " let mean_y_value = calculate_mean(Y_values);\n", " " let mut squared_diff_shape = array::ArrayTrait::new();\n", " squared_diff_shape.append(Y_values.data.len());\n", " let mut squared_diff_vals = array::ArrayTrait::new();\n", " let mut squared_mean_diff_shape = array::ArrayTrait::new();\n", " squared_mean_diff_shape.append(Y_values.data.len());\n", " let mut squared_mean_diff_vals = array::ArrayTrait::new();\n", "\n", " let mut i: u32 = 0;\n", "\n", " loop {\n", " match Y_values_.data.pop_front() {\n", " Option::Some(y_value) => {\n", " let diff_pred = *y_value - *Y_pred_values.data.at(i);\n", " let squared_diff = diff_pred * diff_pred;\n", " squared_diff_vals.append(squared_diff);\n", "\n", " let diff_mean = *y_value - mean_y_value;\n", " let squared_mean_diff = diff_mean * diff_mean;\n", " squared_mean_diff_vals.append(squared_mean_diff);\n", " i += 1;\n", " },\n", " Option::None(_) => { break; }\n", " }\n", " };\n", "\n", " let squared_diff_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(squared_diff_shape.span(), squared_diff_vals.span());\n", " let squared_mean_diff_tensor = TensorTrait::<\n", "
FP16x16\n", " >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.span());\n", " let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_squared_mean_diff = squared_mean_diff_tensor\n", " .cumsum(0, Option::None(()), Option::None(()));\n", " let r_score = FixedTrait::new_unscaled(1, false)\n", " - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n", " / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n", "\n", " return r_score;\n", "}\n", "\n", "\n", " "fn normalize_user_x_inputs(\n", " x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut x_inputs_normalized = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let mut x_min = ArrayTrait::<FP16x16>::new();\n", " let mut x_max = ArrayTrait::<FP16x16>::new();\n", " let mut x_range = ArrayTrait::<FP16x16>::new();\n", " let mut result = ArrayTrait::<FP16x16>::new();\n", "\n", " if original_x_values.shape.len() > 1 {\n", " let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n", " let data_len = *transposed_tensor.shape.at(0); " " let mut i: u32 = 0;\n", " loop {\n", " if i >= data_len {\n", " break ();\n", " }\n", " let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n", " x_min.append(transposed_tensor_row.min_in_tensor());\n", " x_max.append(transposed_tensor_row.max_in_tensor());\n", " x_range\n", " .append(\n", " transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n", " );\n", "
i += 1;\n", " };\n", " let mut x_min_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_min.span());\n", " let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n", " let mut x_range_tensor = TensorTrait::new(\n", " shape: array![data_len].span(), data: x_range.span()\n", " );\n", "\n", " " if x_inputs.shape.len() > 1 {\n", " let mut j: u32 = 0;\n", " loop {\n", " if j >= *x_inputs.shape.at(0) {\n", " break ();\n", " };\n", " let mut row_data = get_tensor_data_by_row(x_inputs, j);\n", " let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n", " let mut k: u32 = 0;\n", "\n", " loop {\n", " if k >= norm_row_data.data.len() {\n", " break ();\n", " };\n", " result.append(*norm_row_data.data.at(k));\n", " k += 1;\n", " };\n", " j += 1;\n", " };\n", " x_inputs_normalized =\n", " TensorTrait::<\n", " FP16x16\n", " >::new(\n", " array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n", " );\n", " };\n", "\n", " " if x_inputs.shape.len() == 1 {\n", " x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n", " };\n", " }\n", "\n", " if original_x_values.shape.len() == 1 {\n", " let mut x_min_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n", " let mut x_max
_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![original_x_values.max_in_tensor()].span());\n", " let mut x_range_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(\n", " shape: array![1].span(),\n", " data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n", " .span()\n", " );\n", " let mut diff = ((x_inputs - x_min_tensor));\n", " x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n", " };\n", " return x_inputs_normalized;\n", "}\n", "\n", "\n", " "fn rescale_predictions(\n", " prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut rescale_predictions = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let mut y_min_array = ArrayTrait::<FP16x16>::new();\n", " let mut y_max_array = ArrayTrait::<FP16x16>::new();\n", " let mut y_range_array = ArrayTrait::<FP16x16>::new();\n", "\n", " let mut y_max = y_values.max_in_tensor();\n", " let mut y_min = y_values.min_in_tensor();\n", " let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n", " " let y_min_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_min].span());\n", " let y_max_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_max].span());\n", " let y_range_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_range].span());\n", "\n", " rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n", "\n", " return rescale_predictions;\n",
"}\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "f728e6b9", "metadata": {}, "source": [ " "\n", "It is <b>recommended</b> to normalize data before passing it to the multiple linear regression model since we will be working with 16x16 fixed point numbers in cairo. This will prevent from having overflow issues as we compute the feature gradient values (some of the calculations involve squaring x values which can be relatively large if not normalized)" ] }, { "cell_type": "code", "execution_count": 34, "id": "9d23a514", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/data_preprocessing.cairo" ] }, { "cell_type": "code", "execution_count": 35, "id": "71453638", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/data_preprocessing.cairo\n" ] } ], "source": [ "\n", "%%writefile multiple_linear_regression/src/data_preprocessing.cairo\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "use multiple_linear_regresion::helper_functions::{\n", " get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n", " normalize_user_x_inputs, rescale_predictions\n", "};\n", "\n", " "
struct Dataset {\n", " x_values: Tensor<FP16x16>,\n", " y_values: Tensor<FP16x16>,\n", "}\n", "\n", " "impl DataPreprocessing of DatasetTrait {\n", " fn normalize_dataset(ref self: Dataset) -> Dataset {\n", " let mut x_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n", " let mut y_values = TensorTrait::<FP16x16>::new(array![1].span(), array![FixedTrait::new(0, false)].span());\n", " " if self.x_values.shape.len() > 1 {\n", " x_values = normalize_feature_data(self.x_values);\n", " y_values = normalize_label_data(self.y_values);\n", " }\n", " " if self.x_values.shape.len() == 1 {\n", " x_values = normalize_label_data(self.x_values);\n", " y_values = normalize_label_data(self.y_values);\n", " }\n", "\n", " return Dataset { x_values, y_values };\n", " }\n", "}\n", "\n", " "fn normalize_feature_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let mut x_min_array = ArrayTrait::<FP16x16>::new();\n", " let mut x_max_array = ArrayTrait::<FP16x16>::new();\n", " let mut x_range_array = ArrayTrait::<FP16x16>::new();\n", " let mut normalized_array = ArrayTrait::<FP16x16>::new();\n", " " let transposed_tensor = tensor_data.transpose(axes: array![1, 0].span());\n", " let tensor_shape = transposed_tensor.shape;\n", " let tensor_row_len = *tensor_shape.at(0); " let tensor_column_len = *tensor_shape.at(1); " " let mut i: u32 = 0;\n", " loop {\n", " if i >= tensor_row_len {\n", " break ();\n", " }\n", " let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n", " x_max_array.append(transposed_tensor_row.max_in_tensor());\n", " x_min_array.append(transposed_tensor_row.min
_in_tensor());\n", " x_range_array\n", " .append(transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor());\n", " i += 1;\n", " };\n", " " let mut x_min = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1, tensor_row_len].span(), data: x_min_array.span());\n", " let mut x_range = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1, tensor_row_len].span(), data: x_range_array.span());\n", " let normalized_tensor = (tensor_data - x_min) / x_range;\n", " return normalized_tensor;\n", "}\n", "\n", " "fn normalize_label_data(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let mut tensor_data_ = tensor_data;\n", " let mut normalized_array = ArrayTrait::<FP16x16>::new();\n", " let mut range = tensor_data.max_in_tensor() - tensor_data.min_in_tensor();\n", " " let mut i: u32 = 0;\n", "\n", " loop {\n", " match tensor_data_.data.pop_front() {\n", " Option::Some(tensor_val) => {\n", " let mut diff = *tensor_val - tensor_data.min_in_tensor();\n", " normalized_array.append(diff / range);\n", " i += 1;\n", " },\n", " Option::None(_) => { break; }\n", " };\n", " };\n", " " let mut normalized_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![tensor_data.data.len()].span(), data: normalized_array.span());\n", " return normalized_tensor;\n", "}\n", "\n" ] }, { "cell_type": "markdown", "id": "97a3109b", "metadata": {}, "source": [ " "\n", "Implement the Multiple Linear Regression functions" ] }, { "cell_type": "code", "execution_count": 36, "id": "253241d2", "metadata": {}, "outputs": [], "source": [ "os.makedirs(f'multiple_linear_regression/src/model/', exist_ok=
True)" ] }, { "cell_type": "code", "execution_count": 37, "id": "820b7925", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/model/multiple_linear_regression_model.cairo" ] }, { "cell_type": "code", "execution_count": 38, "id": "9fe7721f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/model/multiple_linear_regression_model.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression/src/model/multiple_linear_regression_model.cairo\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "use multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\n", "use multiple_linear_regresion::helper_functions::{\n", " get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n", " normalize_user_x_inputs, rescale_predictions\n", "};\n", "\n", "\n", " "
struct MultipleLinearRegressionModel {\n", " coefficients: Tensor<FP16x16>\n", "}\n", "\n", " "impl RegressionOperation of MultipleLinearRegressionModelTrait {\n", " " fn predict(\n", " ref self: MultipleLinearRegressionModel, feature_inputs: Tensor<FP16x16>\n", " ) -> Tensor<FP16x16> {\n", " " let mut prediction_result = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let mut result = ArrayTrait::<FP16x16>::new();\n", " " if feature_inputs.shape.len() > 1 {\n", " let feature_values = add_bias_term(feature_inputs, 1);\n", " let mut data_len: u32 = *feature_values.shape.at(0);\n", " let mut i: u32 = 0;\n", " loop {\n", " if i >= data_len {\n", " break ();\n", " }\n", " let feature_row_values = get_tensor_data_by_row(feature_values, i);\n", " let predicted_values = feature_row_values.matmul(@self.coefficients);\n", " result.append(*predicted_values.data.at(0));\n", " i += 1;\n", " };\n", " prediction_result =\n", " TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![result.len()].span(), data: result.span());\n", " }\n", "\n", " " if feature_inputs.shape.len() == 1 && self.coefficients.data.len() > 1 {\n", " let feature_values = add_bias_term(feature_inputs, 1);\n", " prediction_result = feature_values.matmul(@self.coefficients);\n", " }\n", "\n", " return prediction_result;\n", " }\n", "}\n", "\n", "fn MultipleLinearRegression(dataset: Dataset) -> MultipleLinearRegressionModel {\n", " let x
_values_tranposed = transpose_tensor(dataset.x_values);\n", " let x_values_tranposed_with_bias = add_bias_term(x_values_tranposed, 0);\n", " let decorrelated_x_features = decorrelate_x_features(x_values_tranposed_with_bias);\n", " let coefficients = compute_gradients(\n", " decorrelated_x_features, dataset.y_values, x_values_tranposed_with_bias\n", " );\n", " return MultipleLinearRegressionModel { coefficients };\n", "}\n", "\n", " "fn add_bias_term(x_feature: Tensor<FP16x16>, axis: u32) -> Tensor<FP16x16> {\n", " let mut x_feature_ = x_feature;\n", " let mut tensor_with_bias = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", " let mut result = ArrayTrait::<FP16x16>::new();\n", " " if x_feature.shape.len() > 1 {\n", " let mut index: u32 = 0;\n", " if axis == 1 {\n", " index = 0;\n", " } else {\n", " index = 1;\n", " }\n", " let data_len = *x_feature.shape.at(index); " let mut i: u32 = 0;\n", " loop {\n", " if i >= data_len {\n", " break ();\n", " }\n", " result\n", " .append(FixedTrait::new(65536, false)); " i += 1;\n", " };\n", " if axis == 0 {\n", " let res_tensor = TensorTrait::new(\n", " shape: array![1, data_len].span(), data: result.span()\n", " );\n", " tensor_with_bias =\n", " TensorTrait::concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n", " } else {\n", " let res_tensor = TensorTrait::new(\n", " shape: array![data_len, 1].span(), data: result.span()\n", " );\n", " tensor_with_bias =\n", " TensorTrait::
concat(tensors: array![x_feature, res_tensor].span(), axis: axis);\n", " }\n", " }\n", " " if x_feature.shape.len() == 1 {\n", " let mut j: u32 = 0;\n", " loop {\n", " match x_feature_.data.pop_front() {\n", " Option::Some(x_val) => {\n", " result.append(*x_val);\n", " j += 1;\n", " },\n", " Option::None(_) => { break; }\n", " };\n", " };\n", " result.append(FixedTrait::new(65536, false)); " tensor_with_bias =\n", " TensorTrait::<FP16x16>::new(shape: array![result.len()].span(), data: result.span());\n", " }\n", " return tensor_with_bias;\n", "}\n", "\n", " "fn decorrelate_x_features(x_feature_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let mut input_tensor = x_feature_data;\n", "\n", " let mut i: u32 = 0;\n", " loop {\n", " if i >= *x_feature_data.shape.at(0) {\n", " break ();\n", " }\n", " let mut placeholder = ArrayTrait::<FP16x16>::new();\n", " let mut feature_row_values = get_tensor_data_by_row(input_tensor, i);\n", " let mut feature_squared = feature_row_values.matmul(@feature_row_values);\n", " " if *feature_squared.data.at(0) == FixedTrait::new(0, false) {\n", " feature_squared =\n", " TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", " }\n", " " let mut j: u32 = i + 1;\n", " loop {\n", " if j >= *x_feature_data.shape.at(0) {\n", " break ();\n", " }\n", " let mut remaining_tensor_values = get_tensor_data_by_row(input_tensor, j);\n", " let feature_cross_pro
duct = feature_row_values.matmul(@remaining_tensor_values);\n", " let feature_gradients = feature_cross_product / feature_squared;\n", " remaining_tensor_values = remaining_tensor_values\n", " - (feature_row_values\n", " * feature_gradients); " " let mut k: u32 = 0;\n", " loop {\n", " if k >= remaining_tensor_values.data.len() {\n", " break ();\n", " }\n", " placeholder.append(*remaining_tensor_values.data.at(k));\n", " k += 1;\n", " };\n", "\n", " j += 1;\n", " };\n", " " let mut decorrelated_tensor = TensorTrait::new(\n", " shape: array![*x_feature_data.shape.at(0) - 1 - i, *x_feature_data.shape.at(1)].span(),\n", " data: placeholder.span()\n", " );\n", " let mut original_tensor = input_tensor\n", " .slice(\n", " starts: array![0, 0].span(),\n", " ends: array![i + 1, *x_feature_data.shape.at(1)].span(),\n", " axes: Option::None(()),\n", " steps: Option::Some(array![1, 1].span())\n", " );\n", " input_tensor =\n", " TensorTrait::concat(\n", " tensors: array![original_tensor, decorrelated_tensor].span(), axis: 0\n", " );\n", " i += 1;\n", " };\n", " return input_tensor;\n", "}\n", "\n", " "fn compute_gradients(\n", " decorrelated_x_features: Tensor<FP16x16>,\n", " y_values: Tensor<FP16x16>,\n", " original_x_tensor_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut gradient_values_flipped = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n
", " let mut result = ArrayTrait::<FP16x16>::new();\n", " let mut tensor_y_vals = y_values;\n", " let mut i: u32 = *decorrelated_x_features.shape.at(0);\n", " " loop {\n", " if i <= 0 {\n", " break ();\n", " }\n", " let index_val = i - 1;\n", " let mut decorelated_feature_row_values = get_tensor_data_by_row(\n", " decorrelated_x_features, index_val\n", " ); " let mut decorelated_features_squared = decorelated_feature_row_values\n", " .matmul(@decorelated_feature_row_values);\n", " let mut feature_label_cross_product = tensor_y_vals\n", " .matmul(@decorelated_feature_row_values); " " if *decorelated_features_squared.data.at(0) == FixedTrait::new(0, false) {\n", " decorelated_features_squared =\n", " TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", " }\n", " " let mut single_gradient_value = feature_label_cross_product\n", " / decorelated_features_squared; " result.append(*single_gradient_value.data.at(0));\n", " " let mut original_x_tensor_row_values = get_tensor_data_by_row(\n", " original_x_tensor_values, index_val\n", " );\n", " tensor_y_vals = tensor_y_vals\n", " - (original_x_tensor_row_values\n", " * single_gradient_value); " i -= 1;\n", " };\n", " " let final_gradients = TensorTrait::new(\n", " shape: array![*decorrelated_x_features.shape.at(0)].span(), data: result.span()\n", " );\n", "\n", " let mut reverse_grad_array = ArrayTrait::<FP16x16>::new();\n", " let mut data_len: u32 = final_gradients.data.len();\n", " loop {\n", " if
data_len <= 0 {\n", " break ();\n", " }\n", " let temp_val = data_len - 1;\n", " reverse_grad_array.append(*final_gradients.data.at(temp_val));\n", " data_len -= 1;\n", " };\n", " " let gradient_values_flipped = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![reverse_grad_array.len()].span(), data: reverse_grad_array.span());\n", "\n", " return gradient_values_flipped;\n", "}\n", "\n", "\n", "\n", "\n", "\n", "\n", " " ] }, { "cell_type": "code", "execution_count": 39, "id": "d269825b", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/model.cairo" ] }, { "cell_type": "code", "execution_count": 40, "id": "b762a212", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/model.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression/src/model.cairo\n", "mod multiple_linear_regression_model;" ] }, { "cell_type": "markdown", "id": "f700ee3a", "metadata": {}, "source": [ " "\n", "Running some checks to ensure the model is performing as expected. Some of the checks involve:\n", "- data normalizations checks\n", "- tensor shape/dimension check\n", "- coefficient value and dimension checks \n", "- model accuracy deviance checks" ] }, { "cell_type": "code", "execution_count": 41, "id": "6df3b8c5", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression/src/test.cairo" ] }, { "cell_type": "code", "execution_count": 42, "id": "6ccda27e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression/src/test.cairo\n" ] } ], "source": [ "%%w
ritefile multiple_linear_regression/src/test.cairo\n", "\n", " "use debug::PrintTrait;\n", "use array::{ArrayTrait, SpanTrait};\n", "\n", "\n", "use multiple_linear_regresion::datasets::boston_data::boston_x_features::boston_x_features;\n", "use multiple_linear_regresion::datasets::boston_data::boston_y_labels::boston_y_labels;\n", "use multiple_linear_regresion::datasets::user_inputs_data::user_inputs_boston_data::user_inputs_boston_data;\n", "\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "\n", "use multiple_linear_regresion::model::multiple_linear_regression_model::{\n", " MultipleLinearRegressionModel, MultipleLinearRegression, MultipleLinearRegressionModelTrait\n", "};\n", "use multiple_linear_regresion::data_preprocessing::{Dataset, DatasetTrait};\n", "use multiple_linear_regresion::helper_functions::{get_tensor_data_by_row, transpose_tensor, calculate_mean , \n", "calculate_r_score, normalize_user_x_inputs, rescale_predictions};\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, \n", " FP16x16TensorSub, FP16x16TensorAdd, FP16x16TensorDiv, FP16x16TensorMul};\n", "\n", " " "
fn multiple_linear_regression_test() {\n", "\n", " "\n", "let mut main_x_vals = boston_x_features();\n", "let mut main_y_vals = boston_y_labels();\n", "let mut dataset = Dataset{x_values: main_x_vals,y_values:main_y_vals};\n", "let mut normalized_dataset = dataset.normalize_dataset();\n", "let mut model = MultipleLinearRegression(normalized_dataset);\n", "let mut model_coefficients = model.coefficients;\n", "let mut reconstructed_ys = model.predict (normalized_dataset.x_values);\n", "let mut r_squared_score = calculate_r_score(normalized_dataset.y_values,reconstructed_ys);\n", "r_squared_score.print(); \n", "\n", " "assert(normalized_dataset.x_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized x not between 0-1');\n", "assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized x not between 0-1');\n", "assert(normalized_dataset.y_values.max_in_tensor() <= FixedTrait::new(65536, false), 'normalized y not between 0-1');\n", "assert(normalized_dataset.x_values.min_in_tensor() >= FixedTrait::new(0, false), 'normalized y not between 0-1');\n", " "assert(normalized_dataset.x_values.data.len()== main_x_vals.data.len() && \n", "normalized_dataset.y_values.data.len()== main_y_vals.data.len() , 'normalized data shape mismatch');\n", " "assert(model.coefficients.data.len() == *main_x_vals.shape.at(1)+1, 'coefficient data shape mismatch');\n", " "assert(r_squared_score >= FixedTrait::new(55699, false), 'Boston model acc. less than 84%');\n", "\n", "\n", " "let user_input = user_inputs_boston_data();\n", "let mut normalized_user_x_inputs = normalize_user_x_inputs(user_input, main_x_vals) ;\n", "let mut prediction_result = model.predict (normalized_user_x_inputs); \n", "let mut rescale_prediction = rescale_predictions(prediction_result, main_y_vals);\n", "(*rescale_prediction.data.at(0)).print(); \n", "\n", "\n", "}\n", "\n"
] }, { "cell_type": "code", "execution_count": null, "id": "52ccc81e", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "3a36b2e6", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.4" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "cell_type": "markdown", "id": "151a8d2d", "metadata": {}, "source": [ " " \n", "For this particular tutorial, we will build a Multiple Linear Regression algorithm from scratch and use it to <b>forecast the projected the 7-day lifetime repayments for AAVE's WETH Pool</b>. Toward the end of the tutorial, we will convert the data & model to Cairo enabling us to make the entire Multiple Regression Solver as well as the AAVE's forecasts to be <b>fully Provable and Verifiable. </b>\n", " "In many financial business applications, a vast number of problems can be modeled using <b>Multiple Linear Regression.</b> As we step into the on-chain ProvableML domain, these traditional algorithms may still be essential in addressing forecasting and prediction-related business problems. Interestingly, these may prove to be actually advantageous in on-chain environments as they are relatively interpretable, lightweight and cost-efficient.\n", "\n", "The most common method for computing MLR includes the use of pseudo-inverse or SVD (Singular value decomposition), which can be far more complex to implement than the problem being worked on often times. Hence, the next common approach often preferred are gradient-based methods. These are perfect for large datasets, but they too can be excessive due to the intensive iterative approach they take to approximate gradients; which in the context of on-chain environments can be fairly expensive. \n", "\n", "<b>This repo presents an intuitive a closed-form (non gradient based) approach to computing MLR gradients to allow builders and end-users to interact with MLR systems with ease and transparency. </b>\n", "\n", "The Multiple Linear regression Solver works in three components:\n", "1. Decorrelates x features from one another (most intensive part)\n", "2. Computes the exact gradients between each decorrelated x feature and target y variables in one step\n", "3. Performs predictions and forecasts using th
e computed gradients\n", "\n", " "<b>The key benefit of this Multiple Linear Regression Solver lies in its commitment to <u>Provability and Verifiability</u>. By integrating it into Cairo using the Orion Framework, we allow the entire MLR system to become inherently provable through STARKs, ensuring unparalleled transparency and trustworthiness. This enables every inference of the model construction, execution and prediction to be easily proved using LambdaClass STARK Prover. </b>\n" ] }, { "cell_type": "markdown", "id": "90182f06", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 1, "id": "f09afc09", "metadata": {}, "outputs": [], "source": [ "
import pandas as pd\n", "
import numpy as np\n", "
import matplotlib.pyplot as plt\n", "
import os\n", "from sklearn.metrics
import r2_score" ] }, { "cell_type": "code", "execution_count": 2, "id": "1f1a3299", "metadata": {}, "outputs": [], "source": [ " "df_main= pd.read_csv('AAVE-V3-weth.csv')\n", "df_main.drop('Unnamed: 0', axis=1, inplace=True)" ] }, { "cell_type": "code", "execution_count": 3, "id": "bb21fa7d", "metadata": {}, "outputs": [], "source": [ " "df_main= df_main.iloc[::-1]" ] }, { "cell_type": "code", "execution_count": 4, "id": "1d292060", "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>accruedToTreasury</th>\n", " <th>availableLiquidity</th>\n", " <th>lifetimeFlashLoans</th>\n", " <th>lifetimeLiquidity</th>\n", " <th>lifetimeReserveFactorAccrued</th>\n", " <th>totalLiquidityAsCollateral</th>\n", " <th>totalScaledVariableDebt</th>\n", " <th>lifetimeRepayments</th>\n", " <th>variableBorrowRate</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>30</th>\n", " <td>9.330000e+18</td>\n", " <td>7.400000e+22</td>\n", " <td>1.240000e+23</td>\n", " <td>2.040000e+24</td>\n", " <td>5.500000e+20</td>\n", " <td>1.190000e+24</td>\n", " <td>2.870000e+23</td>\n", " <td>7.640000e+23</t
d>\n", " <td>3.370000e+25</td>\n", " </tr>\n", " <tr>\n", " <th>29</th>\n", " <td>1.340000e+19</td>\n", " <td>7.450000e+22</td>\n", " <td>1.240000e+23</td>\n", " <td>2.050000e+24</td>\n", " <td>5.500000e+20</td>\n", " <td>1.190000e+24</td>\n", " <td>2.870000e+23</td>\n", " <td>7.640000e+23</td>\n", " <td>3.370000e+25</td>\n", " </tr>\n", " <tr>\n", " <th>28</th>\n", " <td>1.740000e+19</td>\n", " <td>8.020000e+22</td>\n", " <td>1.240000e+23</td>\n", " <td>2.070000e+24</td>\n", " <td>5.500000e+20</td>\n", " <td>1.190000e+24</td>\n", " <td>2.880000e+23</td>\n", " <td>7.650000e+23</td>\n", " <td>3.320000e+25</td>\n", " </tr>\n", " <tr>\n", " <th>27</th>\n", " <td>2.120000e+19</td>\n", " <td>9.590000e+22</td>\n", " <td>1.280000e+23</td>\n", " <td>2.120000e+24</td>\n", " <td>5.500000e+20</td>\n", " <td>1.240000e+24</td>\n", " <td>2.860000e+23</td>\n", " <td>7.700000e+23</td>\n", " <td>3.180000e+25</td>\n", " </tr>\n", " <tr>\n", " <th>26</th>\n", " <td>1.660000e+17</td>\n", " <td>1.000000e+23</td>\n", " <td>1.410000e+23</td>\n", " <td>2.150000e+24</td>\n", " <td>5.750000e+20</td>\n", " <td>1.280000e+24</td>\n", " <td>2.870000e+23</td>\n", " <td>7.730000e+23</td>\n", " <td>3.150000e+25</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " accruedToTreasury availableLiquidity lifetimeFlashLoans \\\n", "30 9.330000e+18 7.400000e+22 1.240000e+23 \n",
"29 1.340000e+19 7.450000e+22 1.240000e+23 \n", "28 1.740000e+19 8.020000e+22 1.240000e+23 \n", "27 2.120000e+19 9.590000e+22 1.280000e+23 \n", "26 1.660000e+17 1.000000e+23 1.410000e+23 \n", "\n", " lifetimeLiquidity lifetimeReserveFactorAccrued \\\n", "30 2.040000e+24 5.500000e+20 \n", "29 2.050000e+24 5.500000e+20 \n", "28 2.070000e+24 5.500000e+20 \n", "27 2.120000e+24 5.500000e+20 \n", "26 2.150000e+24 5.750000e+20 \n", "\n", " totalLiquidityAsCollateral totalScaledVariableDebt lifetimeRepayments \\\n", "30 1.190000e+24 2.870000e+23 7.640000e+23 \n", "29 1.190000e+24 2.870000e+23 7.640000e+23 \n", "28 1.190000e+24 2.880000e+23 7.650000e+23 \n", "27 1.240000e+24 2.860000e+23 7.700000e+23 \n", "26 1.280000e+24 2.870000e+23 7.730000e+23 \n", "\n", " variableBorrowRate \n", "30 3.370000e+25 \n", "29 3.370000e+25 \n", "28 3.320000e+25 \n", "27 3.180000e+25 \n", "26 3.150000e+25 " ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df_main.head()" ] }, { "cell_type": "markdown", "id": "4d06feb5", "metadata": {}, "source": [ " ] }, { "cell_type": "markdown", "id": "0eec3df8", "metadata": {}, "source": [ "Now that we have prepared our AAVE dataset, we will use the features to forecast the <b>lifetime Repayments 7 days in advance</b>. In order to achieve this, we take the lifetime R
epayments column and replicate it into a new column whilst shifting the column data upwards by 7 spots. This, will allow us to use this shifted column as our y label and the rest of the data as our X features.\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "3a6dc4ba", "metadata": {}, "outputs": [], "source": [ " " " "factor = 1e+22\n", "df_main = df_main/factor" ] }, { "cell_type": "code", "execution_count": 6, "id": "6b94e8bd", "metadata": {}, "outputs": [], "source": [ "df= df_main.copy()" ] }, { "cell_type": "code", "execution_count": 7, "id": "629ee65a", "metadata": {}, "outputs": [], "source": [ "days_to_forecast = -7\n", "df['lifetimeRepayments_7day_forecast'] = df[['lifetimeRepayments']].shift(days_to_forecast) \n", "df = df[0:days_to_forecast]" ] }, { "cell_type": "code", "execution_count": 8, "id": "1a8ac4af", "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>accruedToTreasury</th>\n", " <th>availableLiquidity</th>\n", " <th>lifetimeFlashLoans</th>\n", " <th>lifetimeLiquidity</th>\n", " <th>lifetimeReserveFactorAccrued</th>\n", " <th>totalLiquidityAsCollateral</th>\n", " <th>totalScaledVariableDebt</th>\n", " <th>lifetimeRepayments</th>\n", " <th>var
iableBorrowRate</th>\n", " <th>lifetimeRepayments_7day_forecast</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>30</th>\n", " <td>0.000933</td>\n", " <td>7.40</td>\n", " <td>12.4</td>\n", " <td>204.0</td>\n", " <td>0.0550</td>\n", " <td>119.0</td>\n", " <td>28.7</td>\n", " <td>76.4</td>\n", " <td>3370.0</td>\n", " <td>77.4</td>\n", " </tr>\n", " <tr>\n", " <th>29</th>\n", " <td>0.001340</td>\n", " <td>7.45</td>\n", " <td>12.4</td>\n", " <td>205.0</td>\n", " <td>0.0550</td>\n", " <td>119.0</td>\n", " <td>28.7</td>\n", " <td>76.4</td>\n", " <td>3370.0</td>\n", " <td>77.4</td>\n", " </tr>\n", " <tr>\n", " <th>28</th>\n", " <td>0.001740</td>\n", " <td>8.02</td>\n", " <td>12.4</td>\n", " <td>207.0</td>\n", " <td>0.0550</td>\n", " <td>119.0</td>\n", " <td>28.8</td>\n", " <td>76.5</td>\n", " <td>3320.0</td>\n", " <td>77.5</td>\n", " </tr>\n", " <tr>\n", " <th>27</th>\n", " <td>0.002120</td>\n", " <td>9.59</td>\n", " <td>12.8</td>\n", " <td>212.0</td>\n", " <td>0.0550</td>\n", " <td>124.0</td>\n", " <td>28.6</td>\n", " <td>77.0</td>\n", " <td>3180.0</td>\n", " <td>77.6</td>\n", " </tr>\n", " <tr>\n", " <th>26</th>\n", " <td>0.000017</td>\n", " <td>10.00</td>\n", " <td>14.1</td>\n", " <td>215.0</td>\n", " <td>0.0575</td>\n", " <td>128.0</td>\n", " <td>28.7</td>\n",
" <td>77.3</td>\n", " <td>3150.0</td>\n", " <td>78.0</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " accruedToTreasury availableLiquidity lifetimeFlashLoans \\\n", "30 0.000933 7.40 12.4 \n", "29 0.001340 7.45 12.4 \n", "28 0.001740 8.02 12.4 \n", "27 0.002120 9.59 12.8 \n", "26 0.000017 10.00 14.1 \n", "\n", " lifetimeLiquidity lifetimeReserveFactorAccrued \\\n", "30 204.0 0.0550 \n", "29 205.0 0.0550 \n", "28 207.0 0.0550 \n", "27 212.0 0.0550 \n", "26 215.0 0.0575 \n", "\n", " totalLiquidityAsCollateral totalScaledVariableDebt lifetimeRepayments \\\n", "30 119.0 28.7 76.4 \n", "29 119.0 28.7 76.4 \n", "28 119.0 28.8 76.5 \n", "27 124.0 28.6 77.0 \n", "26 128.0 28.7 77.3 \n", "\n", " variableBorrowRate lifetimeRepayments_7day_forecast \n", "30 3370.0 77.4 \n", "29 3370.0 77.4 \n", "28 3320.0 77.5 \n", "27 3180.0 77.6 \n", "26 3150.0
78.0 " ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.head()" ] }, { "cell_type": "code", "execution_count": 9, "id": "cf992ac6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(24, 9)\n", "(24,)\n" ] } ], "source": [ " "features = df.drop(['lifetimeRepayments_7day_forecast'], axis=1)\n", " "target = df['lifetimeRepayments_7day_forecast']\n", "\n", "\n", " "X_original = features.to_numpy()\n", "Y_original = target.to_numpy()\n", "\n", "print(X_original.shape)\n", "print(Y_original.shape)" ] }, { "cell_type": "markdown", "id": "d5c31a01", "metadata": {}, "source": [ " "Normalize the data so that all the features values are between 0-1" ] }, { "cell_type": "code", "execution_count": 10, "id": "e4551bc6", "metadata": {}, "outputs": [], "source": [ "def normalize_data(original_data):\n", " data_min = np.min(original_data, axis=0)\n", " data_max = np.max(original_data, axis=0)\n", " data_range = data_max - data_min\n", " data_normalized = (original_data - data_min) / data_range\n", " \n", " return data_normalized\n", " " ] }, { "cell_type": "code", "execution_count": 11, "id": "9a50f392", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Features max value: 1.0\n", "Features min value: 0.0\n", "Labels max value: 1.0\n", "Labels min value: 0.0\n" ] } ], "source": [ " "X_normalized= normalize_data(X_original)\n", "y_normalized= normalize_data(Y_original)\n", "\n", "print('Features max value:', X_normalized.max())\n", "print('Features min value:', X_normalized.min())\n", "print('Labels max value:', y_normali
zed.max())\n", "print('Labels min value:', y_normalized.min())\n" ] }, { "cell_type": "markdown", "id": "310c1a0a", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 12, "id": "8a5a52b6", "metadata": {}, "outputs": [], "source": [ "def transpose_and_add_bias(feature_data):\n", " " transposed_data= feature_data.T\n", " " transposed_data_with_bias = np.vstack((transposed_data, np.ones(transposed_data.shape[1])))\n", " \n", " return transposed_data_with_bias" ] }, { "cell_type": "markdown", "id": "c8d6ed24", "metadata": {}, "source": [ " "It's <b>very important</b> to notice that as we decorrelate the X features, only the last feature row will be fully <b>orthogonal</b>. The rest of the features are decorrelated from one another but <b>are not fully orthogonal to each other</b>. This is done to save on computational cost and make the algorythm more efficient. This will enable us to calculate the following feature gradients much easier and quicker, than if we were to fully orthogonalize all the features and then compute the gradients.\n", "\n", "Later when we compute the gradients we will start from the last fully orthogonalised feature values and walk backwards to calculate the correponding gradinets, whilst removing their component from the y variable. " ] }, { "cell_type": "code", "execution_count": 13, "id": "e3c5b44c", "metadata": {}, "outputs": [], "source": [ "def decorrelate_features(feature_data):\n", "\n", " " x_temp = feature_data.copy()\n", " \n", " " feature_rows = feature_data.shape[0]\n", " \n", " " for i in range(feature_rows):\n", " feature_squared = np.sum(x_temp[i]**2)\n", " for j in range(i+1, feature_rows):\n", " feature_cross_prod = np.sum(x_temp[i] * x_temp[j])\n", " if feature_squared == 0:\n
", " print('Warning, division by zero encountered and handled')\n", " feature_squared = 1e-8 \n", " feature_grad = feature_cross_prod / feature_squared\n", " x_temp[j] -= feature_grad * x_temp[i]\n", " \n", " decorelated_x_vals = x_temp\n", "\n", " return decorelated_x_vals\n" ] }, { "cell_type": "markdown", "id": "74fa9460", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 14, "id": "42de0d6e", "metadata": {}, "outputs": [], "source": [ "def calculate_gradients(decorelated_x_vals, y_values, original_x_features):\n", " \n", " " " y_temp = y_values.copy()\n", " feature_rows = decorelated_x_vals.shape[0]\n", " gradients = np.zeros(feature_rows)\n", "\n", " " for i in range(feature_rows-1, -1, -1):\n", " prod = np.sum(y_temp * decorelated_x_vals[i])\n", " squared = np.sum(decorelated_x_vals[i] * decorelated_x_vals[i])\n", " if squared == 0:\n", " print('Warning, division by zero encountered and handled')\n", " squared = 1e-8\n", "\n", " gradients[i] = prod / squared\n", " y_temp -= gradients[i] * original_x_features[i]\n", " \n", "\n", " return gradients" ] }, { "cell_type": "code", "execution_count": 15, "id": "3c7c3fc3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training data shapes:\n", "X_normalized: (10, 24)\n", "y_normalized: (24,)\n" ] } ], "source": [ "X_normalized_transposed_with_bias = transpose_and_add_bias(X_normalized)\n", "\n", "print(\"Training data shapes:\")\n", "print(\"X_normalized:\", X_normalized_transposed_with_bias.shape)\n", "print(\"y_normalized:\", y_normalized.shape)" ] }, { "cell_type": "code", "exe
cution_count": 16, "id": "f96a6e15", "metadata": {}, "outputs": [], "source": [ "decorrelated_X_features = decorrelate_features(X_normalized_transposed_with_bias)" ] }, { "cell_type": "code", "execution_count": 17, "id": "8815700e", "metadata": {}, "outputs": [], "source": [ "gradient_values = calculate_gradients(decorrelated_X_features, y_normalized, X_normalized_transposed_with_bias )\n" ] }, { "cell_type": "code", "execution_count": 18, "id": "169a41b4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "All regression coefficient: [-1.27062243 1.15931271 0.173401 -0.31112069 1.09338439 0.93959362\n", " -1.12956438 -0.08371113 1.18734043 0.3425375 ]\n" ] } ], "source": [ "real_gradient_values_reversed = np.flip(gradient_values)\n", "print('All regression coefficient: ', real_gradient_values_reversed )" ] }, { "cell_type": "markdown", "id": "d6134a53", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 19, "id": "a1bda8ed", "metadata": {}, "outputs": [], "source": [ "def denormalize_data(original_data,normalized_data):\n", " data_min = np.min(original_data)\n", " data_max = np.max(original_data)\n", " data_range = data_max - data_min\n", " \n", " denormalize_data = ( normalized_data * data_range) + data_min\n", " return denormalize_data" ] }, { "cell_type": "code", "execution_count": 20, "id": "17b37869", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "R^2 score (denormalized): 0.9968099033369738\n" ] }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAkAAAAHFCAYAAAAaD0bAAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAACSm0lEQVR4nOzdd3hT1RvA8W/SvaGFLkZb
NoVCQTbIUPaQJUOQKYIbRKY/9hRQZIiiiCB7iAiKbJlSlmWD7FJWKat7J+f3RyQSW6CBltD2/TxPHppz7z33vWlI3t6zNEophRBCCCFEHqK1dABCCCGEEM+bJEBCCCGEyHMkARJCCCFEniMJkBBCCCHyHEmAhBBCCJHnSAIkhBBCiDxHEiAhhBBC5DmSAAkhhBAiz5EESAghhBB5jiRAIs8KCwtDo9Hw+eefP3Y/f39/evbsaVJ25MgR6tWrh5ubGxqNhhkzZmT6vAkJCYwZM4adO3em27Zw4UI0Gg1hYWGZri+rPHg9Hjy0Wi358+fn1VdfZcuWLc89ntzo9OnTjBkzJtO/3wfvhwcPa2trChcuTK9evbh+/Xr2BvuP/77/d+7ciUajyfD9+zj79u1jzJgxREVFpdtWv3596tev/0xxCmEua0sHIMSLbu3atbi6upqU9e7dm/j4eFasWEH+/Pnx9/fPdH0JCQmMHTsWIN2HfosWLQgJCcHHx+dZw35qH374IV26dEGn0/H3338zduxYmjdvzh9 "text/plain": [ "<Figure size 640x480 with 1 Axes>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "y_pred_norm = gradient_values @ X_normalized_transposed_with_bias "reconstructed_y = denormalize_data(Y_original,y_pred_norm) \n", " "plt.figure(2)\n", "plt.title(\" LifetimeRepayment Predictions\")\n", "plt.plot(reconstructed_y )\n", "plt.plot(Y_original)\n", "plt.legend([\" Actual y values\", \"reconstructed ys (predictions)\"])\n", "plt.xlabel('Days')\n", "plt.ylabel('Lifetime Repayment (thousands ETH)')\n", "\n", " "accuracy_denormalized = r2_score(Y_original, reconstructed_y)\n", "print(\"R^2 score (denormalized):\", accuracy_denormalized)" ] }, { "cell_type": "markdown", "id": "b8296c8b", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": 21, "id": "bb721ff0", "metadata": {}, "outputs": [], "source": [ "df_forecast = df_main[-7:]\n", "df_forecast_data = df_forecast.to_numpy()" ] }, { "cell_type": "code", "execution_count": 22, "id": "5ba45802", "metadata": {}, "outputs": [], "source": [ "X_min = np.min(X_original, axis=0)\n", "X_max = np.max(X_original, axis=0)\n", "X_range = X_max - X_min\n", "df_forecast_data_normalized = (df_forecast_data - X_min) / X_range\n", " ] }, { "cell_type": "code", "execution_count": 23,
"id": "c8d18eb5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training data shapes:\n", "X_normalized: (9, 7)\n", "y_normalized: (10, 7)\n" ] } ], "source": [ " "df_forecast_data_normalized_transposed= df_forecast_data_normalized.T\n", "df_forecast_data_normalized_transposed_with_bias = np.vstack((df_forecast_data_normalized_transposed, np.ones(df_forecast_data_normalized_transposed.shape[1])))\n", "print(\"Training data shapes:\")\n", "print(\"X_normalized:\", df_forecast_data_normalized_transposed.shape)\n", "print(\"y_normalized:\", df_forecast_data_normalized_transposed_with_bias.shape)" ] }, { "cell_type": "code", "execution_count": 24, "id": "5df80bde", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1.0782944838728898\n", "1 1.1357059848525208\n", "2 1.1665048712468642\n", "3 1.193423550976403\n", "4 1.2455779743568984\n", "5 1.3032904853814864\n", "6 1.3668000624508785\n" ] } ], "source": [ "forecast_normalized = gradient_values @ df_forecast_data_normalized_transposed_with_bias\n", "for i in range(len(forecast_normalized)):\n", " print(i,forecast_normalized[i])" ] }, { "cell_type": "code", "execution_count": 25, "id": "84ea2dd4", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tomorrow's Lifetime Repayment from Weth pool Forecast: 95.62317677745183\n", "Day 2 Lifetime Repayment from Weth pool Forecast 96.5934311440076\n", "Day 3 Lifetime Repayment from Weth pool Forecast 97.113932324072\n", "Day 4 Lifetime Repayment from Weth pool Forecast 97.5688580115012\n", "Day 5 Lifetime Repayment from Weth pool Forecast 98.45026776663158\n", "Day 6 Lifetime Repayment from Weth pool Forecast 99.4256092029
4711\n", "Day 7 Lifetime Repayment from Weth pool Forecast 100.49892105541984\n" ] } ], "source": [ " "Y_min = np.min(Y_original, axis=0)\n", "Y_max = np.max(Y_original, axis=0)\n", "Y_range = Y_max - Y_min\n", "\n", "forecast_pred = (forecast_normalized * Y_range) + Y_min\n", " "for i in range(len(forecast_pred)):\n", " if i==0:\n", " print(\"Tomorrow's Lifetime Repayment from Weth pool Forecast: \",forecast_pred[i])\n", " else:\n", " print('Day',i+1,'Lifetime Repayment from Weth pool Forecast',forecast_pred[i])\n", " " ] }, { "cell_type": "code", "execution_count": 26, "id": "01f96e7f", "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAA1IAAAHUCAYAAAAwUBnrAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/P9b71AAAACXBIWXMAAA9hAAAPYQGoP6dpAAC/qklEQVR4nOzdd3iT5frA8W+SZnVvOiht2XvJEJClKHs5QOHIFAciooDiUbSIoqAMJ3pQhojihKOyBFmigExFQGaZbSmU7jZNkzy/P/prDqEttNAF3J/ryiV55/2+aWLuPM9zPxqllEIIIYQQQgghRLFpKzoAIYQQQgghhLjRSCIlhBBCCCGEECUkiZQQQgghhBBClJAkUkIIIYQQQghRQpJICSGEEEIIIUQJSSIlhBBCCCGEECUkiZQQQgghhBBClJAkUkIIIYQQQghRQpJICSGEEEIIIUQJSSIlRAVbuHAhGo2myMebb755xf03btzosr3BYCAoKIh27drx4osvcvLkyXK6koKKuqbAwMAKi6m8xMXFERMTw969e0u032effUZQUBDp6ekF1uXm5hISEoJGo+Hbb7+96rEuXLiA0WhEo9Gwc+dO5/Lz589jMBh48MEHi9w3LS0Nd3d3+vTpA1z973Tjxo3OfaOiooiJiSn+RRfhwIEDxMTEcOLEiWs+xsqVK687lmHDhhEVFXXFbcaMGYNGoyEhIcFl+cWLF9Fqtej1ejIyMlzWnTlzBo1Gw7PPPgvAiRMnrniPY2JiCrzfr/SA/71ul77+l+rVq9dVr62oexAVFcWwYcNclu3Zs4eOHTvi4+ODRqNhzpw5Vz12vqysLOc1Xi7/Oq7nb+FaXf66aLVa/Pz8uOuuu/j555/LPZ6b0ZXe6w8 "text/plain": [ "<Figure size 1000x500 with 1 Axes>" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "forecast_plot_data = np.insert(forecast_pred, 0, Y_original[-1])\n", "\n", " "residual = Y_original - reconstructed_y\n", "stderr = np.std(residual)\n", "z_score = 1.96 "interv
als = z_score *stderr * np.sqrt(np.arange(len(forecast_plot_data)))\n", "\n", "\n", " "plt.figure(figsize=(10, 5))\n", "plt.plot(Y_original , label='Historical lifetime repayments')\n", "plt.plot(len(Y_original)-1 + np.arange(len(forecast_plot_data)), forecast_plot_data , color='orange', label='Upcoming 7 day forecast')\n", "plt.fill_between(len(Y_original)-1 + np.arange(len(forecast_plot_data)), \n", " (forecast_plot_data - intervals),\n", " (forecast_plot_data + intervals),\n", " alpha=0.12,\n", " color='green',\n", " label='95% confidence interval')\n", "\n", "\n", "plt.plot(reconstructed_y , label=\"Model's Predictions\", color='lightblue')\n", " "plt.xlabel('Days')\n", "plt.ylabel('Lifetime Repayment (thousands ETH)')\n", "plt.title(\" 7 Day Forecast (AAVE's total WETH lifetimeRepayment)\")\n", "plt.legend()\n", "\n", " "plt.show()" ] }, { "cell_type": "markdown", "id": "8af06223", "metadata": {}, "source": [ " " "\n", "Scarb is the Cairo package manager specifically created to streamline our Cairo and Starknet development process. You can find all information about Scarb and Cairo installation here" ] }, { "cell_type": "code", "execution_count": 27, "id": "9d3cb826", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created `multiple_linear_regression_aave` package.\n" ] } ], "source": [ "! scarb new multiple_linear_regression_aave" ] }, { "cell_type": "code", "execution_count": 28, "id": "df9e40c3", "metadata": {}, "outputs": [], "source": [ "!echo -n > multiple_linear_regression_aave/src/lib.cairo" ] }, { "cell_type": "markdown", "id": "38ac62e4", "metadata": {}, "source": [ "A new project folder will be created for you and make sure to replace the con
tent in Scarb.toml file with the following code:\n", "```toml\n", "[package]\n", "name = \"multiple_linear_regresion\"\n", "version = \"0.1.0\"\n", "\n", "\n", "[dependencies]\n", "orion = { git = \"https: "\n", "[scripts]\n", "test = \"scarb cairo-test -f multiple_linear_regression_test\"\n", "```" ] }, { "cell_type": "code", "execution_count": 29, "id": "e366fe1f", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (252576425.py, line 3)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn [29], line 3\u001b[0;36m\u001b[0m\n\u001b[0;31m mod test;\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ " "%%writefile -a src/lib.cairo \n", "mod test;\n", "mod data_preprocessing;\n", "mod helper_functions;\n", "mod datasets;\n", "mod model;" ] }, { "cell_type": "markdown", "id": "c0340f15", "metadata": {}, "source": [ "\n", " "\n", "Now, we will transition our model to cairo. We will start by converting the the X features and Y labels to FP16x16 tensors numbers. " ] }, { "cell_type": "code", "execution_count": 30, "id": "39b6b561", "metadata": {}, "outputs": [], "source": [ " "\n", "\n", "def generate_cairo_files(data, name, folder_name):\n", " \n", " os.makedirs(f'multiple_linear_regression_aave/src/datasets/{folder_name}', exist_ok=True)\n", " with open(os.path.join('multiple_linear_regression_aave/src/datasets', f'{folder_name}', f\"{name}.cairo\"), \"w\") as f:\n", " f.write(\n", " \"use array::ArrayTrait;\\n\" +\n", " \"use orion::numbers::fixed_point::implementations::fp16x16::core::{FP16x16Impl, FP16x16PartialEq };\\n\" +\n", " \"use orion::operators::tensor::{Tensor, Tens
orTrait, FP16x16Tensor};\\n\" +\n", " \"use orion::numbers::{FP16x16, FixedTrait};\\n\\n\" +\n", " \"fn {0}() -> Tensor<FP16x16> \".format(name) + \"{\\n\" +\n", " \" let tensor = TensorTrait::<FP16x16>::new( \\n\"\n", " )\n", " \n", " if len(data.shape)>1:\n", " f.write(\" shape: array![{0},\".format(data.shape[0]))\n", " f.write(\"{0}].span(),\\n\".format(data.shape[1]))\n", " f.write(\n", " \" data: array![ \\n\"\n", " )\n", " if len(data.shape)==1:\n", " f.write(\" shape: array![{0}].span(),\\n\".format(data.shape[0]))\n", " f.write(\n", " \" data: array![ \\n\"\n", " )\n", " for val in np.nditer(data.flatten()):\n", " f.write(\" FixedTrait::new({0}, {1} ),\\n\".format(abs(int(val * 2**16)), str(val < 0).lower()))\n", " f.write(\n", " \"].span() \\n \\n\" +\n", " \");\\n\\n\"+\n", " \"return tensor; \\n\"+\n", " \"}\"\n", " )\n", " with open(os.path.join('multiple_linear_regression_aave/src/datasets', f'{folder_name}.cairo'), 'a') as f:\n", " f.write(f\"mod {name};\\n\")" ] }, { "cell_type": "code", "execution_count": 31, "id": "1a0e7a71", "metadata": {}, "outputs": [], "source": [ "generate_cairo_files(X_original, 'aave_x_features', 'aave_data')\n", "generate_cairo_files(Y_original, 'aave_y_labels', 'aave_data')\n" ] }, { "cell_type": "code", "execution_count": 32, "id": "b8c2b804", "metadata": {}, "outputs": [], "source": [ "generate_cairo_files(df_forecast_data, 'aave_weth_revenue_data_input', 'user_inputs_data')" ] }, { "cell_type": "code", "execution_count": 33,
"id": "fb316caf", "metadata": {}, "outputs": [], "source": [ " "! touch multiple_linear_regression_aave/src/datasets.cairo" ] }, { "cell_type": "code", "execution_count": 34, "id": "fa5fb2be", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression_aave/src/datasets.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression_aave/src/datasets.cairo\n", "mod aave_data;\n", "mod user_inputs_data;" ] }, { "cell_type": "code", "execution_count": 35, "id": "b9af5716", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression_aave/src/datasets/aave_data.cairo" ] }, { "cell_type": "code", "execution_count": 36, "id": "230ac6ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression_aave/src/datasets/aave_data.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression_aave/src/datasets/aave_data.cairo\n", "mod aave_x_features;\n", "mod aave_y_labels;" ] }, { "cell_type": "code", "execution_count": 37, "id": "4d57b462", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo" ] }, { "cell_type": "code", "execution_count": 38, "id": "fe4d136a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression_aave/src/datasets/user_inputs_data.cairo\n", "mod aave_weth_revenue_data_input;" ] }, { "cell_type": "markdown", "id": "8cb7f589", "metadata": {}, "source": [ " "\n", "We add some helper functions to make i
t easier to construct our MLR model" ] }, { "cell_type": "code", "execution_count": 39, "id": "cd34a054", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression_aave/src/helper_functions.cairo" ] }, { "cell_type": "code", "execution_count": 40, "id": "a9d33776", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression_aave/src/helper_functions.cairo\n" ] } ], "source": [ "%%writefile multiple_linear_regression_aave/src/helper_functions.cairo\n", "\n", "use debug::PrintTrait;\n", "use array::{ArrayTrait, SpanTrait};\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "\n", " "fn get_tensor_data_by_row(tensor_data: Tensor<FP16x16>, row_index: u32,) -> Tensor<FP16x16> {\n", " let column_len = *tensor_data.shape.at(1); " " let mut result = ArrayTrait::<FP16x16>::new();\n", " " let mut i: u32 = 0;\n", " loop {\n", " if i >= column_len {\n", " break ();\n", " }\n", " result.append(tensor_data.at(indices: array![row_index, i].span()));\n", " i += 1;\n", " };\n", " let resultant_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(array![column_len].span(), data: result.span());\n", " return resultant_tensor;\n", "}\n", "\n", "\n", " "fn transpose_tensor(tensor_data: Tensor<FP16x16>) -> Tensor<FP16x16> {\n", " let tensor_transposed = tensor_data.transpose(axes: array![1, 0].span());\n", " return tensor_transposed;\n", "}\n", "\n", "fn calculate_mean(tensor_data: Tensor<FP16x16>) -> FP16x16 {\n", " let te
nsor_size = FixedTrait::<FP16x16>::new_unscaled(tensor_data.data.len(), false);\n", " let cumulated_sum = tensor_data.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_result = cumulated_sum.data[tensor_data.data.len() - 1];\n", " let mean = *sum_result / tensor_size;\n", " return mean;\n", "}\n", "\n", " "fn calculate_r_score(Y_values: Tensor<FP16x16>, Y_pred_values: Tensor<FP16x16>) -> FP16x16 {\n", " let mut Y_values_ = Y_values;\n", " let mean_y_value = calculate_mean(Y_values);\n", " " let mut squared_diff_shape = array::ArrayTrait::new();\n", " squared_diff_shape.append(Y_values.data.len());\n", " let mut squared_diff_vals = array::ArrayTrait::new();\n", " let mut squared_mean_diff_shape = array::ArrayTrait::new();\n", " squared_mean_diff_shape.append(Y_values.data.len());\n", " let mut squared_mean_diff_vals = array::ArrayTrait::new();\n", "\n", " let mut i: u32 = 0;\n", "\n", " loop {\n", " match Y_values_.data.pop_front() {\n", " Option::Some(y_value) => {\n", " let diff_pred = *y_value - *Y_pred_values.data.at(i);\n", " let squared_diff = diff_pred * diff_pred;\n", " squared_diff_vals.append(squared_diff);\n", "\n", " let diff_mean = *y_value - mean_y_value;\n", " let squared_mean_diff = diff_mean * diff_mean;\n", " squared_mean_diff_vals.append(squared_mean_diff);\n", " i += 1;\n", " },\n", " Option::None(_) => { break; }\n", " }\n", " };\n", "\n", " let squared_diff_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(squared_diff_shape.span(), squared_diff_vals.span());\n", " let squared_mean_diff_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(squared_mean_diff_shape.span(), squared_mean_diff_vals.sp
an());\n", " let sum_squared_diff = squared_diff_tensor.cumsum(0, Option::None(()), Option::None(()));\n", " let sum_squared_mean_diff = squared_mean_diff_tensor\n", " .cumsum(0, Option::None(()), Option::None(()));\n", " let r_score = FixedTrait::new_unscaled(1, false)\n", " - *sum_squared_diff.data.at(Y_values.data.len() - 1)\n", " / *sum_squared_mean_diff.data.at(Y_values.data.len() - 1);\n", "\n", " return r_score;\n", "}\n", "\n", "\n", " "fn normalize_user_x_inputs(\n", " x_inputs: Tensor<FP16x16>, original_x_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut x_inputs_normalized = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let mut x_min = ArrayTrait::<FP16x16>::new();\n", " let mut x_max = ArrayTrait::<FP16x16>::new();\n", " let mut x_range = ArrayTrait::<FP16x16>::new();\n", " let mut result = ArrayTrait::<FP16x16>::new();\n", "\n", " if original_x_values.shape.len() > 1 {\n", " let transposed_tensor = original_x_values.transpose(axes: array![1, 0].span());\n", " let data_len = *transposed_tensor.shape.at(0); " " let mut i: u32 = 0;\n", " loop {\n", " if i >= data_len {\n", " break ();\n", " }\n", " let mut transposed_tensor_row = get_tensor_data_by_row(transposed_tensor, i);\n", " x_min.append(transposed_tensor_row.min_in_tensor());\n", " x_max.append(transposed_tensor_row.max_in_tensor());\n", " x_range\n", " .append(\n", " transposed_tensor_row.max_in_tensor() - transposed_tensor_row.min_in_tensor()\n", " );\n", " i += 1;\n", " };\n", " let mut x_min_tensor = TensorTrait::new(shap
e: array![data_len].span(), data: x_min.span());\n", " let mut x_max_tensor = TensorTrait::new(shape: array![data_len].span(), data: x_max.span());\n", " let mut x_range_tensor = TensorTrait::new(\n", " shape: array![data_len].span(), data: x_range.span()\n", " );\n", "\n", " " if x_inputs.shape.len() > 1 {\n", " let mut j: u32 = 0;\n", " loop {\n", " if j >= *x_inputs.shape.at(0) {\n", " break ();\n", " };\n", " let mut row_data = get_tensor_data_by_row(x_inputs, j);\n", " let mut norm_row_data = (row_data - x_min_tensor) / x_range_tensor;\n", " let mut k: u32 = 0;\n", "\n", " loop {\n", " if k >= norm_row_data.data.len() {\n", " break ();\n", " };\n", " result.append(*norm_row_data.data.at(k));\n", " k += 1;\n", " };\n", " j += 1;\n", " };\n", " x_inputs_normalized =\n", " TensorTrait::<\n", " FP16x16\n", " >::new(\n", " array![*x_inputs.shape.at(0), *x_inputs.shape.at(1)].span(), data: result.span()\n", " );\n", " };\n", "\n", " " if x_inputs.shape.len() == 1 {\n", " x_inputs_normalized = (x_inputs - x_min_tensor) / x_range_tensor;\n", " };\n", " }\n", "\n", " if original_x_values.shape.len() == 1 {\n", " let mut x_min_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![original_x_values.min_in_tensor()].span());\n", " let mut x_max_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array
![1].span(), data: array![original_x_values.max_in_tensor()].span());\n", " let mut x_range_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(\n", " shape: array![1].span(),\n", " data: array![original_x_values.max_in_tensor() - original_x_values.min_in_tensor()]\n", " .span()\n", " );\n", " let mut diff = ((x_inputs - x_min_tensor));\n", " x_inputs_normalized = ((x_inputs - x_min_tensor)) / x_range_tensor;\n", " };\n", " return x_inputs_normalized;\n", "}\n", "\n", "\n", " "fn rescale_predictions(\n", " prediction_result: Tensor<FP16x16>, y_values: Tensor<FP16x16>\n", ") -> Tensor<FP16x16> {\n", " let mut rescale_predictions = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![FixedTrait::new(10, false)].span());\n", "\n", " let mut y_min_array = ArrayTrait::<FP16x16>::new();\n", " let mut y_max_array = ArrayTrait::<FP16x16>::new();\n", " let mut y_range_array = ArrayTrait::<FP16x16>::new();\n", "\n", " let mut y_max = y_values.max_in_tensor();\n", " let mut y_min = y_values.min_in_tensor();\n", " let mut y_range = y_values.max_in_tensor() - y_values.min_in_tensor();\n", " " let y_min_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_min].span());\n", " let y_max_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_max].span());\n", " let y_range_tensor = TensorTrait::<\n", " FP16x16\n", " >::new(shape: array![1].span(), data: array![y_range].span());\n", "\n", " rescale_predictions = (prediction_result * y_range_tensor) + y_min_tensor;\n", "\n", " return rescale_predictions;\n", "}\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "22a08ab
f", "metadata": {}, "source": [ " "\n", "It is <b>recommended</b> to normalize data before passing it to the multiple linear regression model since we will be working with 16x16 fixed point numbers in cairo. This will prevent from having overflow issues as we compute the feature gradient values (some of the calculations involve squaring x values which can be relatively large if not normalized)" ] }, { "cell_type": "code", "execution_count": 41, "id": "9995e498", "metadata": {}, "outputs": [], "source": [ "! touch multiple_linear_regression_aave/src/data_preprocessing.cairo" ] }, { "cell_type": "code", "execution_count": 42, "id": "f559dab1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting multiple_linear_regression_aave/src/data_preprocessing.cairo\n" ] } ], "source": [ "\n", "%%writefile multiple_linear_regression_aave/src/data_preprocessing.cairo\n", "\n", "use orion::operators::tensor::{\n", " Tensor, TensorTrait, FP16x16Tensor, U32Tensor, U32TensorAdd, FP16x16TensorSub, FP16x16TensorAdd,\n", " FP16x16TensorDiv, FP16x16TensorMul\n", "};\n", "use orion::numbers::{FP16x16, FixedTrait};\n", "use multiple_linear_regresion::helper_functions::{\n", " get_tensor_data_by_row, transpose_tensor, calculate_mean, calculate_r_score,\n", " normalize_user_x_inputs, rescale_predictions\n", "};\n", "\n", " "