Professional Documents
Culture Documents
Data generation and visualization (a) Generate 100 random numbers whose elements are uniformly distributed in the interval (0,1), and show histogram of the numbers. Hint: rand, answer: a=rand(100,1) hist(a,10)
(b) Suppose a probabilistic variable y obeys y = 4 sin(6x) + e, where e obeys a normal distribution whose mean and variance are 0 and 1, respectively. Plot 100 pairs of x and y as shown in Fig. 1.2. Finally, suppose y' = 4 sin(6x) (noiseless), and superpose 100 pairs of x and y' over the same figure. Answer:
2. Function approximation (fitting) (a) Prepare for a dataset (x,y) as follows. The input variable x follows a uniformly distribution whose interval is (0,1), and the output variable y = 4 sin(6x) + epsilon, where epsilon follows a normal distribution whose mean and variance are 0 and 1. Generate 100 pairs of x and y. Answer: x=rand(1,100);
(b) Prepare for 10 training data (x and y pairs) by random sampling from the dataset generated in (a), and use the remaining 90 data as test data. Answer:
ny=4*sin(6*x); trainx=[]; trainy=[]; n=100; for i=1:10 num=randi(1,n); trainx=[trainx,x(num)]; x(num)=[]; trainy=[trainy,y(num)]; y(num)=[]; n=n-1; end xy; train=[trainx;trainy]; test=[x;y]; ny;
(c) Obtain parameter w by polynomial fitting in case of the polynomial order M = 0,1,3,5,8 and 9. answer: M=0 : M=1 : M=3 : M=5 : 1.0102 -9.0024 5.0725 69.2155 -2.9976 110.1246 -5.9401
286.1493 -324.3433
4.0984
-4.3076
2.5792
-0.8890
0.1678
-7.0300 0.0001
7.0829
-4.2885
1.6009
-0.3639
M=[0,1,3,5,8,9]; err=[]; for i=1:size(M,2) plot(test(1,:),test(2,:)) hold on plot(xy(1,:),ny) p=polyfit(train(1,:),train(2,:),M(i)) f=polyval(p,x); if M(i)==0 f=f*ones(1,size(x,2)); end hold on plot(x,f);legend('Data','Noiseless','Fitted');xlabel('x');ylabel('y'); er=sqrt(sum((((f-y).*(f-y))/size(x,2)))); err=[err,er]; input('save, close figure and press enter','s'); end
(d) Plot the fitted polynomial curves, data, and the noiseless curve simultaneously in a panel, for each order. Answer: M=0
M=1
M=3
M=5
M=8
M=9
plot(M,err);xlabel('M');ylabel('E_{rms}'); legend('Error');