-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensor_creation.cpp
More file actions
73 lines (55 loc) · 2.03 KB
/
Copy pathtensor_creation.cpp
File metadata and controls
73 lines (55 loc) · 2.03 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "tensor.h" // Include the provided Tensor class
#include <algorithm>
#include <random>
namespace ts {
// Helper function to calculate total size from shape
size_t totalSize(const std::vector<size_t>& shape) {
return std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());
}
// Random Tensor Creation
template <typename T>
Tensor rand(const std::vector<size_t>& shape) {
size_t total = totalSize(shape);
std::vector<double> data(total);
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
for (size_t i = 0; i < total; ++i) {
data[i] = distribution(generator);
}
return Tensor(shape, "double", data);
}
// Zero Tensor Creation
template <typename T>
Tensor zeros(const std::vector<size_t>& shape) {
size_t total = totalSize(shape);
std::vector<double> data(total, 0.0);
return Tensor(shape, "double", data);
}
// One Tensor Creation
template <typename T>
Tensor ones(const std::vector<size_t>& shape) {
size_t total = totalSize(shape);
std::vector<double> data(total, 1.0);
return Tensor(shape, "double", data);
}
// Full Tensor Creation
template <typename T>
Tensor full(const std::vector<size_t>& shape, T value) {
size_t total = totalSize(shape);
std::vector<double> data(total, static_cast<double>(value));
return Tensor(shape, "double", data);
}
// Identity Matrix Creation
template <typename T>
Tensor eye(const std::vector<size_t>& shape) {
if (shape.size() != 2 || shape[0] != shape[1]) {
throw std::invalid_argument("Identity matrix must be square.");
}
size_t total = totalSize(shape);
std::vector<double> data(total, 0.0);
for (size_t i = 0; i < shape[0]; ++i) {
data[i * shape[0] + i] = 1.0;
}
return Tensor(shape, "double", data);
}
}