24小时热门版块排行榜    

查看: 3590  |  回复: 12

liangboliu

银虫 (小有名气)

[交流] 【原创】分享一个matlab编写的模糊KNN的例子,经过验证效果不错。 已有12人参与

分享一个模糊KNN的例子,经过测试效果不错。
建议大家在使用的时候,引用一下作者的文章。
function [predicted,memberships, numhits] = fknn(data, labels, test, ...
            testlabels, k_values, info, fuzzy)
% FKNN Fuzzy k-nearest neighbor classification algorithm.
%         Y = FKNN(DATA, LABELS, TEST, TESTLABELS, K, INFO) Runs fuzzy
%         k-nearest neighbors on the given data. DATA is a N-by-D data matrix
%         consisting of N patterns each of which is D-dimensional. LABELS is a
%         N-vector containing the class labels (1,2,...,C) for each pattern.
%        TEST is a M-by-D matrix consisting of M test patterns. TESTLABELS
%        is an optional M-vector for the true class labels of the given test
%        data. If you don't have true labels, just give an empty matrix for this
%        TESTLABELS.
%        K is the number of nearest neighbors to look at.
%        The algorithm will print an information line at every INFO test
%        patterns, if INFO>0. If INFO is zero, nothing will be printed.
%        Y is a M-vector containing the predicted class labels for the given test
%        patterns.
%
%         [Y,MEMS,HITS] = FKNN(DATA, LABELS, TEST, TESTLABELS, K, INFO) returns
%         the fuzzy class-memberships values in MEMS, for each test pattern. It is
%         a M-by-C matrix, C being the number of classes.
%        HITS is the number of correctly predicted test patterns. Note that HITS
%        is meaningless if TESTLABELS is not provided.
%
%         [Y,MEMS,HITS] = FKNN(DATA, LABELS, TEST, TESTLABELS, K, INFO, FUZZY) If
%         you don't want to do "fuzzy" k-nn, then give FUZZY as 'false'.
%
%        This m-file is capable of testing several k-values simultaneously. If
%        you pass a vector of k-values, rather than a single scalar, in K, then
%        each output variable is populated accordingly. So, if you give K as
%        [5 10 15], then Y becomes M-by-3, MEMS M-by-C-by-3 and HITS  3-by-1.
%
%        References:
%        J. M. Keller, M. R. Gray, and J. A. Givens, Jr.,
%        "A Fuzzy K-Nearest Neighbor Algorithm",
%        IEEE Transactions on Systems, Man, and Cybernetics,
%        Vol. 15, No. 4, pp. 580-585.  
%
% TODO: Generalize this m-file to Lp norm
%
% Emre Akbas [eakbas2 @ uiuc.edu]  Dec 2006.
%

if nargin<7
    fuzzy = true;
end

num_train = size(data,1);
num_test  = size(test,1);

% scaling factor for fuzzy weights. see [1] for details
m = 2;

% convert class labels to unary membership vectors (of 1s and 0s)
max_class = max(labels);
temp = zeros(length(labels),max_class);
for i=1:num_train
    temp(i, = [zeros(1, labels(i)-1) 1 zeros(1,max_class - labels(i))];
end
labels = temp;
clear temp;

% allocate space for storing predicted labels
predicted = zeros(num_test, length(k_values));

% allocate space for 'numhits'. This will only be used if 'testlabels' is
% provided
numhits = zeros(length(k_values),1);

% will the memberships be stored? if yes, allocate space
store_memberships = false;
if nargout > 1,
    store_memberships=true;
    memberships = zeros(num_test, max_class, length(k_values));
end

%% BEGIN kNN
% for each test point, do:
t0=clock;
tstart = t0;
for i=1:num_test
    distances = (repmat(test(i,, num_train,1) - data).^2;
    % for efficiency, no need to take sqrt since it is a non-decreasing function
    distances = sum(distances,2)';

    % sort the distances
    [junk, indeces] = sort(distances);

    for k=1:length(k_values)
        neighbor_index = indeces(1:k_values(k));
        weight = ones(1,length(neighbor_index));
        if fuzzy,
            % originally, this weight calculation should be:
            % weight = distances(neighbor_index).^(-2/(m-1));
            % but since we didn't take sqrt above and the inverse 2th power
            % the weights are:
            % weight = sqrt(distances(neighbor_index)).^(-2/(m-1));
            % which is equaliavent to:
            weight = distances(neighbor_index).^(-1/(m-1));

            % set the Inf (infite) weights, if there are any, to  1.
            if max(isinf(weight))
                warning(['Some of the weights are Inf for sample: ' ...
                        num2str(i) '. These weights are set to 1.']);
                weight(isinf(weight))=1;
            end
        end
        test_out = weight*labels(neighbor_index,/(sum(weight));

        if store_memberships, memberships(i,:,k) = test_out; end;

        % find predicted class (the one with the max. fuzzy vote)
        [junk, index_of_max] = max(test_out');

        predicted(i,k) = index_of_max;

        % compute current hit rate, if test labels are given
        if ~isempty(testlabels) && predicted(i,k)==testlabels(i)
            numhits(k) = numhits(k)+1;
        end
    end

    % print info
    if mod(i,info)==0
        elapsed = etime(clock, t0);
        fprintf(1,['%dth sample done.  Elapsed (from previous info): %.2f' ...
            ' sn.  Estimated left: %.2f sn.\n\tHit rate(s) so far:   '], ...
            i, elapsed, etime(clock, tstart)*((num_test-i)/i) );
        for k=1:length(k_values)
            fprintf(1,'%3d: %.3f\t',k_values(k), 100*numhits(k)/i);
        end
        fprintf(1,'\n');

        t0=clock; % start timer again
    end
end
回复此楼

» 猜你喜欢

» 本主题相关价值贴推荐,对您同样有帮助:

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

stephenliu89

银虫 (小有名气)


小木虫(金币+0.5):给个红包,谢谢回帖交流
顶下!比我用C++写的那个简易的好!
Email:stephenliu1989@163.com
2楼2010-09-14 10:53:39
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
谢谢分享
3楼2010-10-29 11:04:41
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

qiaoyinhu

木虫 (正式写手)

不错,谢谢分享!
4楼2010-11-29 22:28:35
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
谢谢分享!
5楼2011-04-14 10:07:40
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

tywww

铁杆木虫 (小有名气)


小木虫(金币+0.5):给个红包,谢谢回帖
不错,下来看看! ,谢谢分享!
6楼2012-03-06 21:20:55
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

苏素2006

木虫 (小有名气)


小木虫: 金币+0.5, 给个红包,谢谢回帖
谢谢分享
[zeros(1, labels(i)-1) 1 zeros(1,max_class - labels(i))];
这一句是不是有问题?

[ Last edited by 苏素2006 on 2013-1-8 at 21:44 ]
7楼2013-01-08 21:22:36
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

sandyuu

新虫 (初入文坛)

8楼2013-01-21 15:19:36
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

zzpnlz

木虫 (正式写手)

楼主贡献良多
天下英雄出我辈,一入江湖岁月催
9楼2013-01-21 20:11:39
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

june_522

新虫 (初入文坛)

谢谢分享,学习了
10楼2014-03-06 16:52:43
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
相关版块跳转 我要订阅楼主 liangboliu 的主题更新
普通表情 高级回复 (可上传附件)
最具人气热帖推荐 [查看全部] 作者 回/看 最后发表
[考研] 281求调剂(0805) +9 烟汐忆海 2026-03-16 19/950 2026-03-19 11:42 by laoshidan
[考研] 328求调剂,英语六级551,有科研经历 +4 生物工程调剂 2026-03-16 12/600 2026-03-19 11:10 by 生物工程调剂
[考研] 材料专硕英一数二306 +5 z1z2z3879 2026-03-18 5/250 2026-03-19 07:43 by BruceLiu320
[考研] 材料工程专硕调剂 +5 204818@lcx 2026-03-17 6/300 2026-03-18 22:55 by 204818@lcx
[考研] 330求调剂 +3 小材化本科 2026-03-18 3/150 2026-03-18 21:55 by 无懈可击111
[考研] 材料专业求调剂 +5 hanamiko 2026-03-18 5/250 2026-03-18 20:19 by 星空星月
[考研] 材料与化工一志愿南昌大学327求调剂推荐 +8 Ncdx123456 2026-03-13 9/450 2026-03-18 14:40 by haxia
[考研] 331求调剂(0703有机化学 +7 ZY-05 2026-03-13 8/400 2026-03-18 14:13 by 007_lilei
[考研] 0703化学调剂 +4 pupcoco 2026-03-17 7/350 2026-03-18 12:14 by djl2006
[考研] 0703化学336分求调剂 +6 zbzihdhd 2026-03-15 7/350 2026-03-18 09:53 by zhukairuo
[考研] 296求调剂 +5 大口吃饭 身体健 2026-03-13 5/250 2026-03-17 21:05 by 不惑可乐
[考研] 梁成伟老师课题组欢迎你的加入 +8 一鸭鸭哟 2026-03-14 10/500 2026-03-17 15:07 by 一鸭鸭哟
[考研] 211本,11408一志愿中科院277分,曾在中科院自动化所实习 +6 Losir 2026-03-12 7/350 2026-03-17 12:09 by danranxie
[考研] 材料工程专硕274一志愿211求调剂 +6 薛云鹏 2026-03-15 6/300 2026-03-17 11:05 by 学员h26Tkc
[考研] 304求调剂 +5 素年祭语 2026-03-15 5/250 2026-03-16 17:00 by 我的船我的海
[考研] 一志愿211 0703方向310分求调剂 +3 努力奋斗112 2026-03-15 3/150 2026-03-16 16:44 by houyaoxu
[考研] 285求调剂 +6 ytter 2026-03-12 6/300 2026-03-16 15:05 by njzyff
[考研] 277材料科学与工程080500求调剂 +3 自由煎饼果子 2026-03-16 3/150 2026-03-16 14:10 by 运气yunqi
[考研] 289求调剂 +4 这么名字咋样 2026-03-14 6/300 2026-03-14 18:58 by userper
[考研] 求材料调剂 085600英一数二总分302 前三科235 精通机器学习 一志愿哈工大 +4 林yaxin 2026-03-12 4/200 2026-03-13 22:04 by 星空星月
信息提示
请填处理意见