caffe 用matlab解析日志画loss和accuracy

时间:2022-02-24 08:10:19
 clc;  
    clear;  
      
    % load the log file of caffe model  
    fid = fopen('log-previous-insulator.txt', 'r');  
    tline = fgetl(fid);  
      
    accuracyIter =[];
    accuracyArray =[];
    lossIter = [];
    lossArray = [];
    
    %record the last line  
    lastLine = '';  
      
    %read line  
    while ischar(tline)  
        %%%%%%%%%%%%%% the accuracy line %%%%%%%%%%%%%%  
        k = strfind(tline, 'Test net output');  
        if (k)  
            k = strfind(tline, 'accuracy');  
            if (k)  
                % If the string contain test and accuracy at the same time  
                % The bias from 'accuracy' to the float number  
                indexStart = k + 11;   
                indexEnd = size(tline);  
                str = tline(indexStart : indexEnd(2));  
                accuracyArray = [accuracyArray, str2num(str)];  
            end  
              
            % Get the number of index  
            k = strfind(lastLine, 'Iteration');  
            if (k)  
                indexStart = k + 10;  
                indexEnd = strfind(lastLine, '(');  
                str2 = lastLine(indexStart : indexEnd - 1);  
                accuracyIter  = [accuracyIter, str2num(str2)];  
            end  
              
            % Concatenation of two string  
            res_str = strcat(str2, '/', str);  
        end  
          
        %%%%%%%%%%%%%% the loss line %%%%%%%%%%%%%%  
        k1 = strfind(tline, 'Iteration');  
        if (k1)  
           k2 = strfind(tline, 'loss');  
           if (k2)  
               indexStart = k2 + 7;  %loss位置到数据位置起始位置相差7位
               indexEnd = size(tline);  
          str1 = tline(indexStart:indexEnd(2));  %数据开始位置到结束位置,就是loss,也就是纵坐标
               indexStart = k1 + 10;  %从iteration到迭代次数数据起始位相差10位
               indexEnd = strfind(tline, '(') - 1; %找到左括号位置-1:根据你的txt来看是括号还是逗号
               str2 = tline(indexStart:indexEnd);  %从起始位置到结束位置为迭代次数,也就是横坐标
               res_str1 = strcat(str2, '/', str1);  %把横纵坐标连接起来
               lossIter  = [lossIter,  str2num(str2)];  %把迭代次数转化为数据赋值给lossiter
               lossArray = [lossArray, str2num(str1)];  %把loss转化为数据复给lossArray
           end  
        end  
          
        lastLine = tline;  
        tline = fgetl(fid);      
    end  
      
    %draw figure  
    figure;h1 = plot(accuracyIter, accuracyArray);title('iteration vs accurancy');  %绘制accuracy曲线  
    figure;h2 = plot(lossIter, lossArray);title('iteration vs loss');   %绘制loss曲线
    print(2,'-dpng','iteration vs loss')%保存