-
Notifications
You must be signed in to change notification settings - Fork 0
/
tensor.c
55 lines (48 loc) · 1.54 KB
/
tensor.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdlib.h>
#include <time.h>
#include "tensor.h"
// so far only supports 1D tensors, tomorrow? idk
TensorPtr Tensor_create(int size, double data[]){
TensorPtr newTensor = (TensorPtr) malloc(sizeof(Tensor) + sizeof(ValuePtr[size]));
newTensor->size = size;
for(int i = 0; i < size; i++){
newTensor->elements[i] = Value_create(data[i]);
}
return newTensor;
}
TensorPtr Tensor_create_empty(int size){
TensorPtr newTensor = (TensorPtr) malloc(sizeof(Tensor) + sizeof(ValuePtr[size]));
newTensor->size = size;
return newTensor;
}
TensorPtr Tensor_create_random(int size){
srand(time(NULL));
TensorPtr newTensor = (TensorPtr) malloc(sizeof(Tensor) + sizeof(ValuePtr[size]));
newTensor->size = size;
for(int i = 0; i < size; i++){
newTensor->elements[i] = Value_create(gen_random());
}
return newTensor;
}
TensorPtr Tensor_create_zeros(int size){
TensorPtr newTensor = (TensorPtr) malloc(sizeof(Tensor) + sizeof(ValuePtr[size]));
newTensor->size = size;
for(int i = 0; i < size; i++){
newTensor->elements[i] = Value_create(0);
}
return newTensor;
}
void Tensor_print(TensorPtr tensor){
printf("[%.2f", tensor->elements[0]->data);
for(int i = 1; i < tensor->size; i++){
printf(", %.2f", tensor->elements[i]->data);
}
printf("]\n");
}
void Tensor_print_grad(TensorPtr tensor){
printf("[%.2f", tensor->elements[0]->grad);
for(int i = 1; i < tensor->size; i++){
printf(", %.2f", tensor->elements[i]->grad);
}
printf("]\n");
}