矩阵乘法编写,从文件输入输出

题目

matrixA.txt , shape(1,50)
matrixB.txt , shape(50,10)
1. 讀取matrixA.txt,matrixB.txt中的矩陣
2. 進行矩陣乘法 - matrixA * matrixB
3. 將得到的矩陣數值,由小到大排序後輸出至ans_one.txt,每个数字要换行

文件样式

  • matrixA.txt
    这里写图片描述
    -matrixB.txt
    这里写图片描述

直接上代码

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

using namespace std;
//忽视硬编码
//1*50
ifstream matrixFile1("/home/wuxiao/MyGithub/ML/homework1/2017ML_HW0_data/matrixA.txt");
//50*10
ifstream matrixFile2("/home/wuxiao/MyGithub/ML/homework1/2017ML_HW0_data/matrixB.txt");
ofstream outputFile("/home/wuxiao/MyGithub/ML/homework1/2017ML_HW0_data/Q1_ans.txt");
vector<int> matrixANum;
vector<int> matrixBNum;
vector<int> outputFileNum;

void splitString(const string& s, vector<int>& v, const string& c)
{
    string::size_type pos1, pos2;
    pos2 = s.find(c);
    pos1 = 0;
    while(string::npos != pos2)
    {
        v.push_back(strtoll(s.substr(pos1, pos2-pos1).c_str(),NULL,10));


        pos1 = pos2 + c.size();
        pos2 = s.find(c, pos1);
    }
    if(pos1 != s.length())
    {
        v.push_back(strtoll(s.substr(pos1).c_str(),NULL,10));
    }
}

void getFileNumToArray(ifstream &file,int row,vector<int> &output)
{
    string tempString = "";
    for(int i=0;i<row;i++)
    {
        getline(file,tempString);
        splitString(tempString,output,",");
    }

}

void getOutputNum(vector<int> &file1,vector<int> &file2,int times,vector<int> &outputFile)
{
    for(int i=0;i<times;i++)
    {
        int sum = 0;
        for(size_t j=0;j<file1.size();j++)
        {
            sum += file1[j] * file2[file1.size() * i + j];

        }
        outputFile.push_back(sum);
    }
    sort(outputFile.begin(),outputFile.end());
}

int main() {
    if(!matrixFile1 || !matrixFile2 || !outputFile)
    {
        cout<<"unable to open inputFile or outputFile!"<<endl;
        return -1;
    }

    //读取输入文件的value到数组
    getFileNumToArray(matrixFile1,1,matrixANum);
    getFileNumToArray(matrixFile2,50,matrixBNum);

    //计算矩阵乘积结果
    getOutputNum(matrixANum,matrixBNum,10,outputFileNum);

    //输出写入文件
    vector<int>::iterator iter = outputFileNum.begin();
    for(iter = outputFileNum.begin();iter != outputFileNum.end();iter++)
    {
        outputFile<<*iter<<'\n';
    }
    return 0;
}
Hadoop编写矩阵乘法的一般步骤如下: 1. 将矩阵数据按行块划分为多个文件,每个文件包含一部分行数据。这样可以将大矩阵分解为小矩阵,方便并行计算。 2. Map阶段:每个Mapper读取一组矩阵,将其转换为稠密矩阵或稀疏矩阵,并将其转化为键值对(key-value)。其中键表示矩阵中每个元素所在的行和列,值表示该元素的值。 3. Shuffle阶段:将Map输出的键值对按照键进行排序,并按照键分组,每组对应一个Reducer。 4. Reduce阶段:对于每个Reducer,将其对应的所有键值对中的值进行乘法运算,最终得到输出的结果。 以下是Hadoop编写矩阵乘法的示例代码: Mapper部分: ```java public class MatrixMapper extends Mapper<LongWritable, Text, Text, Text> { private Text outKey = new Text(); private Text outValue = new Text(); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // 读取输入矩阵数据 String[] tokens = value.toString().split(","); String matrixName = tokens[0]; int row = Integer.parseInt(tokens[1]); int col = Integer.parseInt(tokens[2]); int val = Integer.parseInt(tokens[3]); // 将矩阵数据转换为键值对 if (matrixName.equals("A")) { for (int i = 1; i <= col; i++) { outKey.set(row + "," + i); outValue.set(matrixName + "," + col + "," + val); context.write(outKey, outValue); } } else { for (int i = 1; i <= row; i++) { outKey.set(i + "," + col); outValue.set(matrixName + "," + row + "," + val); context.write(outKey, outValue); } } } } ``` Reducer部分: ```java public class MatrixReducer extends Reducer<Text, Text, Text, Text> { private Text outKey = new Text(); private Text outValue = new Text(); @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { // 从输入的键值对中矩阵数据 List<String> listA = new ArrayList<>(); List<String> listB = new ArrayList<>(); for (Text value : values) { String[] tokens = value.toString().split(","); String matrixName = tokens[0]; int len = Integer.parseInt(tokens[1]); int val = Integer.parseInt(tokens[2]); // 将矩阵数据按照矩阵名称分别存储 if (matrixName.equals("A")) { listA.add(len + "," + val); } else { listB.add(len + "," + val); } } // 对于每个矩阵元素进行乘法运算 int result = 0; for (String a : listA) { String[] tokensA = a.split(","); int lenA = Integer.parseInt(tokensA[0]); int valA = Integer.parseInt(tokensA[1]); for (String b : listB) { String[] tokensB = b.split(","); int lenB = Integer.parseInt(tokensB[0]); int valB = Integer.parseInt(tokensB[1]); if (lenA == lenB) { result += valA * valB; } } } // 输出结果 outKey.set(key); outValue.set(String.valueOf(result)); context.write(outKey, outValue); } } ``` Driver部分: ```java public class MatrixMultiplication { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "matrix multiplication"); job.setJarByClass(MatrixMultiplication.class); job.setMapperClass(MatrixMapper.class); job.setReducerClass(MatrixReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 以上代码仅供参考,实际情况需要根据具体需求进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值