Skip to content

Instantly share code, notes, and snippets.

@cryptospectrum
Created July 14, 2013 21:21
Show Gist options
  • Save cryptospectrum/5996146 to your computer and use it in GitHub Desktop.
Save cryptospectrum/5996146 to your computer and use it in GitHub Desktop.
Analyze Midi Files with Machine Leaning Algorithms
midi_fname='Scarlatti_Sonata_Longo483_K322.mid';
% MIDI scripts from: http://www.kenschutte.com/midi
midi = readmidi(midi_fname);
Notes = midiInfo(midi,0);
%diff start and stop times
dNo5=diff(Notes(:,5));
dNo6=diff(Notes(:,6));
% To Reconstruct Time Data
% [Notes(1,5); cumsum(dNo5)];
% [Notes(1,6); cumsum(dNo6)+Notes(1,6)];
%blim=60;% Middle C
blim=55;% G55 195.9977179909 Hz
bind=find(Notes(1:end-1,3)<blim);
tind=find(Notes(1:end-1,3)>=blim);
for in=1:size(Notes,1)
if(Notes(in,3)<blim)
blb(in)=1;
else
blb(in)=0;
end
end
dNossm = [ones(size(dNo5,1),1) dNo5 dNo6];
% SCRIPT URL @ http://cs229.stanford.edu/materials.html
[theta, loglike] = log_regression(dNossm,blb(1:end-1));
% Logistic Regression with modified sigmoid function,
% same as log_regression() except sigmoid() replaced with modified sigmoid
[thetaM, loglikeM] = log_regressionM(dNossm,blb(1:end-1));
% Train Support Vector Machine with CVX
% CVX @ http://cvxr.com/cvx/
NX = [dNo5 dNo6];
% FOR SVM, LABELS ARE MAPPED FROM [0,1] TO [-1,1]
ylab = 2*(blb(1:end-1)-0.5)';
% C is SVM Classifier value
C = 1;
m = size(NX,1);
n = size(NX,2);
cvx_begin
variables w(n) b xi(m)
minimize 1/2*sum(w.*w) + C*sum(xi)
ylab.*(NX*w + b) >= 1 - xi;
xi >= 0;
cvx_end
xp = linspace(min(NX(:,1)), max(NX(:,1)), 100);
yp = - (w(1)*xp + b)/w(2);
yp1 = - (w(1)*xp + b - 1)/w(2);
yp0 = - (w(1)*xp + b + 1)/w(2);
slope1=-theta(2)/theta(3)
slope2=-thetaM(2)/thetaM(3)
slope3=-w(1)/w(2)
% PLOTTING_______________________________________________________
hold on
plot(dNo5(bind),dNo6(bind),'rx','LineWidth',1.5);
plot(dNo5(tind),dNo6(tind),'go','LineWidth',1.5);
text(0.15,-2.05,strcat(num2str(length(unique(dNo5))), ' unique start intervals'));
text(0.15,-2.35,strcat(num2str(length(unique(dNo6))), ' unique stop intervals'));
text(0.15,-2.65, strcat('Slopes = ',num2str(slope1), ' ,', ...
num2str(slope2), ' ,',num2str(slope3)));
sx = min(dNossm(:,2)):.01:max(dNossm(:,2));
sy = -theta(1)/theta(3)-theta(2)/theta(3)*sx;
sy2 = -thetaM(1)/thetaM(3)-thetaM(2)/thetaM(3)*sx;
plot(sx,sy, '.k','LineWidth',1.5);
plot(sx,sy2, '.c','LineWidth',1.5);
plot(xp, yp, '-b', xp, yp1, '--r', xp, yp0, '--g', 'LineWidth',1.5);
title('Midi File Scarlatti K322, Note Start/Stop Time Differences', 'FontSize', 13)
legend('Notes Below G 55, 195.9 Hz','Notes Above G 55','Logistic Regression(LR)', 'LR Modified Sigmoid', 'Support Vector Machine(SVM)', 'SVM C=1', 'SVM C=1');
xlabel('diff(start time)');
ylabel('diff(stop time)');
axis tight;
box on;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment