Advertisement
Trainlover08

Untitled

Mar 20th, 2024
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. vector<vector<double>> transpose(const vector<vector<double>>& matrix){
  7. unsigned short rows = matrix.size();
  8. unsigned short cols = matrix[0].size();
  9.  
  10. vector<vector<double>> transposed(cols, vector<double>(rows));
  11.  
  12. for(unsigned char i = 0; i < rows; ++i){
  13. for(char j = 0; j < cols; ++j){
  14. transposed[j][i] = matrix[i][j];
  15. }
  16. }
  17.  
  18. return transposed;
  19. }
  20.  
  21. vector<vector<double>> dot_product(const vector<vector<double>>& inputs, const vector<vector<double>>& weights){
  22. short input_rows = inputs.size();
  23. short input_cols = inputs[0].size();
  24. short weight_rows = weights.size();
  25. short weight_cols = weights[0].size();
  26.  
  27. vector<vector<double>> transposed_weights = transpose(weights);
  28.  
  29. if(input_cols != transposed_weights.size()){
  30. printf("Shape error\n");
  31. exit(1);
  32. }
  33.  
  34. vector<vector<double>> result(input_rows, vector<double>(weight_cols, 0.0));
  35.  
  36. for(char i = 0; i < input_rows; ++i){
  37. for(char j = 0; j < weight_rows; ++j){
  38. for(char k = 0; k < input_cols; ++k){
  39. if(k < input_cols && j < weight_cols){
  40. result[i][j] += inputs[i][k] * transposed_weights [j][k];
  41. }
  42. }
  43. }
  44. }
  45.  
  46. return result;
  47. }
  48.  
  49. int main(){
  50. vector<vector<double>> inputs = {
  51. {1., 2., 3., 2.5},
  52. {2. , 5. , -1., 2.},
  53. {-1.5 , 2.7 , 3.3, -0.8}
  54. };
  55. vector<vector<double>> weights = {
  56. {0.2, 0.8, -0.5, 1.},
  57. {0.5, -0.91, 0.26, -0.5},
  58. {-0.26, -0.27, 0.17, 0.87}
  59. };
  60. vector<double> biases = {2, 3, 0.5};
  61. vector<vector<double>> result = dot_product(inputs, weights);
  62. for(char i = 0; i < result.size(); ++i){
  63. for(char j = 0; j < result.size(); ++j){
  64. result[i][j] += biases[j];
  65. }
  66. }
  67. printf("Should be right: %f \n", result[2][3]);
  68. return 0;
  69. }
  70.  
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement