卷积神经网络(ConvNets)中卷积的实现

#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <vector>

void Conv(std::vector<std::vector<int> > &vv_image, std::vector<std::vector<int> > &vv_filter, std::vector<std::vector<int> > &Feature_map) {
    size_t new_col=vv_image.at(0).size()-vv_filter.at(0).size()+1;
    size_t new_row=vv_image.size()-vv_filter.size()+1;
    for(size_t i=0; i<new_row; ++i) {
        std::vector<int> v_tmp;
        v_tmp.clear();
        for(size_t j=0; j<new_col; ++j) {
            int sum_tmp=0;
            for(size_t k=0; k<vv_filter.size(); ++k) {
                for(size_t l=0; l<vv_filter.at(0).size(); ++l) {
                    sum_tmp += vv_filter.at(k).at(l) * vv_image.at(i+k).at(j+l);
                }
            }
            v_tmp.push_back(sum_tmp);
        }
        Feature_map.push_back(v_tmp);
    } 
}

template <class T>
void ReadMatFromFile(std::string &filename, std::vector<std::vector<T> > &lines_feat) {
    std::ifstream vm_info(filename.c_str());
    std::string lines;
    T var;
    std::vector<T> row;

    lines_feat.clear();

    while(!vm_info.eof()) {
        getline(vm_info, lines);
        if(lines.empty())
            break;
        std::replace(lines.begin(), lines.end(), ',', ' ');
        std::stringstream stringin(lines);
        row.clear();

        while(stringin >> var) {
            row.push_back(var);
        }
        lines_feat.push_back(row);
    }
}

template <class T>
void Display2DVector(const std::vector<std::vector<T> > &vv) {
    for(size_t i=0;i<vv.size();++i) {
        for(typename::std::vector<T>::const_iterator it=vv.at(i).begin();it!=vv.at(i).end();++it) {
            std::cout<<*it<<" ";
        }
        std::cout<<"
";
    }
    std::cout<<"--------the total of the 2DVector is "<<vv.size()<<std::endl;
}

int main() {
    std::string image_data("image.dat"), filter_data("filter.dat");
    std::vector<std::vector<int> > vv_image, vv_filter;

    ReadMatFromFile(image_data, vv_image);
    ReadMatFromFile(filter_data, vv_filter);    

    std::vector<std::vector<int> > Feature_map;

    Conv(vv_image, vv_filter, Feature_map);
    Display2DVector(Feature_map);

    return 0;
}
原文地址:https://www.cnblogs.com/donggongdechen/p/11473819.html