Andrew NG 机器学习 练习8-Anomaly Detection and Recommender Systems
来源:互联网 发布:淘宝助理上传很慢 编辑:程序博客网 时间:2024/05/22 00:46
1 Anomaly detection
实现一个异常检测算法检测服务器的异常行为
特征是 每个服务器的 吞吐量(throughput)(mb/s) 和 相应延迟(ms)
采集 m=307 台运行中的服务器的特征,{
其中大部分是 normal 的服务器特征
你将使用 高斯模型 检测数据集中的异常样例
从 2D 数据集开始,以便可视化算法过程
在那个数据集中你将拟合一个高斯分布,发现低可能性的值,从而找出异常样例
之后,你将在一个大的多维数据集中应用异常检测算法
首先可视化数据,如图:
%% ================== Part 1: Load Example Dataset ===================% We start this exercise by using a small dataset that is easy to% visualize.%% Our example case consists of 2 network server statistics across% several machines: the latency and throughput of each machine.% This exercise will help us find possibly faulty (or very fast) machines.%fprintf('Visualizing example dataset for outlier detection.\n\n');% The following command loads the dataset. You should now have the% variables X, Xval, yval in your environmentload('ex8data1.mat');% Visualize the example datasetplot(X(:, 1), X(:, 2), 'bx');axis([0 30 0 30]);xlabel('Latency (ms)');ylabel('Throughput (mb/s)');fprintf('Program paused. Press enter to continue.\n');pause
1.1 Gaussian distribution
为了实施异常检测,你需要首先 根据数据分布,拟合一个模型
给一个训练集 {
需要对每一个特征
对于每一个特征,需要计算参数
通常如果我们认为变量 x 符合高斯分布 x~N(μ,σ2) 则其概率密度函数为:
1.2 Estimating parameters for a Gaussian
通过下列公式计算每个特征的
%% ================== Part 2: Estimate the dataset statistics ===================% For this exercise, we assume a Gaussian distribution for the dataset.%% We first estimate the parameters of our assumed Gaussian distribution, % then compute the probabilities for each of the points and then visualize % both the overall distribution and where each of the points falls in % terms of that distribution.%fprintf('Visualizing Gaussian fit.\n\n');% Estimate my and sigma2[mu sigma2] = estimateGaussian(X);% Returns the density of the multivariate normal at each data point (row) % of Xp = multivariateGaussian(X, mu, sigma2);% Visualize the fitvisualizeFit(X, mu, sigma2);xlabel('Latency (ms)');ylabel('Throughput (mb/s)');fprintf('Program paused. Press enter to continue.\n');pause;
estimateGaussian.m
function [mu sigma2] = estimateGaussian(X)%ESTIMATEGAUSSIAN This function estimates the parameters of a %Gaussian distribution using the data in X% [mu sigma2] = estimateGaussian(X), % The input X is the dataset with each n-dimensional data point in one row% The output is an n-dimensional vector mu, the mean of the data set% and the variances sigma^2, an n x 1 vector% % Useful variables[m, n] = size(X);% You should return these values correctlymu = zeros(n, 1);sigma2 = zeros(n, 1);% ====================== YOUR CODE HERE ======================% Instructions: Compute the mean of the data and the variances% In particular, mu(i) should contain the mean of% the data for the i-th feature and sigma2(i)% should contain variance of the i-th feature.%mu=1/m*sum(X);sigma2=1/m*sum((X-repmat(mu,m,1)).^2);% =============================================================end
1.3 Selecting the threshold, ε
现在我们有了高斯参数,我们就可以调查一下那些样例根据这个分布有高可能性,那些样例有非常低的可能性。有低可能性的样例更有可能是异常的。
决定那些是异常的,一种方法是 根据 交叉验证集 选择一个 阈值。
这部分,实现一个算法选择 ,在交叉验证集中使用 F1 值 来选择 阈值ε。
交叉验证集 {
标签 y=1 表示是异常样例,y=0 表示是正常样例
对于每一个交叉验证集,计算 p(
所有的
- tp 是正确的积极判定(true positives)的数量:标签表明是异常,算法正确分类为异常
- fp 是错误的积极判定(false positives)的数量:标签表明是正常,算法错误的分类为异常
- fn 是错误的消极判定(false negatives)的数量:标签表明是异常,算法错误的分类为正常
%% ================== Part 3: Find Outliers ===================% Now you will find a good epsilon threshold using a cross-validation set% probabilities given the estimated Gaussian distribution% pval = multivariateGaussian(Xval, mu, sigma2);[epsilon F1] = selectThreshold(yval, pval);fprintf('Best epsilon found using cross-validation: %e\n', epsilon);fprintf('Best F1 on Cross Validation Set: %f\n', F1);fprintf(' (you should see a value epsilon of about 8.99e-05)\n');fprintf(' (you should see a Best F1 value of 0.875000)\n\n');% Find the outliers in the training set and plot theoutliers = find(p < epsilon);% Draw a red circle around those outliershold onplot(X(outliers, 1), X(outliers, 2), 'ro', 'LineWidth', 2, 'MarkerSize', 10);hold offfprintf('Program paused. Press enter to continue.\n');pause;
selectThreshold.m
function [bestEpsilon bestF1] = selectThreshold(yval, pval)%SELECTTHRESHOLD Find the best threshold (epsilon) to use for selecting%outliers% [bestEpsilon bestF1] = SELECTTHRESHOLD(yval, pval) finds the best% threshold to use for selecting outliers based on the results from a% validation set (pval) and the ground truth (yval).%bestEpsilon = 0;bestF1 = 0;F1 = 0;stepsize = (max(pval) - min(pval)) / 1000;%计算步长for epsilon = min(pval):stepsize:max(pval) % ====================== YOUR CODE HERE ====================== % Instructions: Compute the F1 score of choosing epsilon as the % threshold and place the value in F1. The code at the % end of the loop will compare the F1 score for this % choice of epsilon and set it to be the best epsilon if % it is better than the current choice of epsilon. % % Note: You can use predictions = (pval < epsilon) to get a binary vector % of 0's and 1's of the outlier predictions predictions = (pval < epsilon);%概率小于阈值的数量,即预测为异常的数量 fp = sum((predictions == 1) & (yval == 0));%算法错误的分类为异常,标签表明是正常 fn = sum((predictions == 0) & (yval == 1));%算法正确分类为正常,标签表明是异常 tp = sum((predictions == 1) & (yval == 1));%算法正确分类为异常,标签表明是异常 prec = tp / (tp + fp);%准确率 rec = tp / (tp + fn);%召回率 F1 = 2 * prec * rec / (prec + rec);%F1值 % ============================================================= if F1 > bestF1 bestF1 = F1; bestEpsilon = epsilon; endendend
1.4 High dimensional dataset
将前面实现的异常检测算法应用在一个更现实、更难的数据集。
一个样例有11个特征,捕捉了服务器更多的属性。
%% ================== Part 4: Multidimensional Outliers ===================% We will now use the code from the previous part and apply it to a % harder problem in which more features describe each datapoint and only % some features indicate whether a point is an outlier.%% Loads the second dataset. You should now have the% variables X, Xval, yval in your environmentload('ex8data2.mat');% Apply the same steps to the larger dataset[mu sigma2] = estimateGaussian(X);% Training set p = multivariateGaussian(X, mu, sigma2);% Cross-validation setpval = multivariateGaussian(Xval, mu, sigma2);% Find the best threshold[epsilon F1] = selectThreshold(yval, pval);fprintf('Best epsilon found using cross-validation: %e\n', epsilon);fprintf('Best F1 on Cross Validation Set: %f\n', F1);fprintf(' (you should see a value epsilon of about 1.38e-18)\n');fprintf(' (you should see a Best F1 value of 0.615385)\n');fprintf('# Outliers found: %d\n\n', sum(p < epsilon));
Best epsilon found using cross-validation: 1.377229e-18Best F1 on Cross Validation Set: 0.615385 (you should see a value epsilon of about 1.38e-18) (you should see a Best F1 value of 0.615385)# Outliers found: 117
2 Recommender Systems
这部分,你将实现协同过滤学习算法,并将其应用在一个电影评分数据集中。
评分范围是1到5。
有
在练习的下一部分,你将实现 cofiCostFunc.m 方法,计算协同过滤目标函数和梯度。之后使用 vfmincg.m 学习协同过滤的参数。
2.1 Movie ratings dataset
从 ex8 movies.mat 读取变量 Y 和 R 。
Y矩阵(num_movies × num_users) 保存 评分
R矩阵是一个0-1标记矩阵,R(i,j)=1 表示 用户 j 给电影 i 评过分;R(i,j)=0 相反。
协同过滤的目标是预测 没有被评分,(即R(i,j)=0 )位置的评分。这样就可以推荐预测用户评分最高的电影给这个用户了。
通过这部分练习,你将用 X 和 Theta 这两个矩阵工作:
X矩阵的第 i 行 对应 第 i 个电影的特征向量
Theta矩阵的 第 j 行对用 第 j 个用户的参数向量
这个练习中 特征数 n=100,相应的 X 是一个
%% =============== Part 1: Loading movie ratings dataset ================% You will start by loading the movie ratings dataset to understand the% structure of the data.% fprintf('Loading movie ratings dataset.\n\n');% Load dataload ('ex8_movies.mat');% Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies on % 943 users%% R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a% rating to movie i% From the matrix, we can compute statistics like average rating.fprintf('Average rating for movie 1 (Toy Story): %f / 5\n\n', ... mean(Y(1, R(1, :))));%取Y中第一行中所有有效评分求均值% We can "visualize" the ratings matrix by plotting it with imagescimagesc(Y);ylabel('Movies');xlabel('Users');fprintf('\nProgram paused. Press enter to continue.\n');pause;
2.2 Collaborative filtering learning algorithm
协同过滤算法在设置电影推荐考虑一套 n维参数向量
模型预测用户 j 对电影 i 的评分,
给一个数据集包含一些用户对一些电影的评分,我们希望学习参数向量
cofiCostFunc.m 计算协同过滤的代价函数和梯度。为了使用现成的最小化函数如fmincg,需要将矩阵展开成单个向量参数。在神经网络编程中也使用过这种方式。
2.2.1 Collaborative filtering cost function
协同过滤代价函数(不带正则化):
应该现在应该定义 cofiCostFunc.m 来返回代价 J。注意你计算用户 j 对电影 i 的代价仅当 R(i,j)=1 时。
2.2.2 Collaborative filtering gradient
代价函数的梯度:
2.2.3 Regularized cost function
协同过滤代价函数(带正则化):
2.2.4 Regularized gradient
带正则化的代价函数的梯度:
%% ============ Part 2: Collaborative Filtering Cost Function ===========% You will now implement the cost function for collaborative filtering.% To help you debug your cost function, we have included set of weights% that we trained on that. Specifically, you should complete the code in % cofiCostFunc.m to return J.% Load pre-trained weights (X, Theta, num_users, num_movies, num_features)load ('ex8_movieParams.mat');% Reduce the data set size so that this runs fasternum_users = 4; num_movies = 5; num_features = 3;X = X(1:num_movies, 1:num_features);Theta = Theta(1:num_users, 1:num_features);Y = Y(1:num_movies, 1:num_users);R = R(1:num_movies, 1:num_users);% Evaluate cost functionJ = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ... num_features, 0);fprintf(['Cost at loaded parameters: %f '... '\n(this value should be about 22.22)\n'], J);fprintf('\nProgram paused. Press enter to continue.\n');pause;%% ============== Part 3: Collaborative Filtering Gradient ==============% Once your cost function matches up with ours, you should now implement % the collaborative filtering gradient function. Specifically, you should % complete the code in cofiCostFunc.m to return the grad argument.% fprintf('\nChecking Gradients (without regularization) ... \n');% Check gradients by running checkNNGradientscheckCostFunction;fprintf('\nProgram paused. Press enter to continue.\n');pause;%% ========= Part 4: Collaborative Filtering Cost Regularization ========% Now, you should implement regularization for the cost function for % collaborative filtering. You can implement it by adding the cost of% regularization to the original cost computation.% % Evaluate cost functionJ = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ... num_features, 1.5);fprintf(['Cost at loaded parameters (lambda = 1.5): %f '... '\n(this value should be about 31.34)\n'], J);fprintf('\nProgram paused. Press enter to continue.\n');pause;%% ======= Part 5: Collaborative Filtering Gradient Regularization ======% Once your cost matches up with ours, you should proceed to implement % regularization for the gradient. %% fprintf('\nChecking Gradients (with regularization) ... \n');% Check gradients by running checkNNGradientscheckCostFunction(1.5);fprintf('\nProgram paused. Press enter to continue.\n');pause;
cofiCostFunc.m
function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ... num_features, lambda)%COFICOSTFUNC Collaborative filtering cost function% [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...% num_features, lambda) returns the cost and gradient for the% collaborative filtering problem.%% Unfold the U and W matrices from paramsX = reshape(params(1:num_movies*num_features), num_movies, num_features);Theta = reshape(params(num_movies*num_features+1:end), ... num_users, num_features);% You need to return the following values correctlyJ = 0;X_grad = zeros(size(X));Theta_grad = zeros(size(Theta));% ====================== YOUR CODE HERE ======================% Instructions: Compute the cost function and gradient for collaborative% filtering. Concretely, you should first implement the cost% function (without regularization) and make sure it is% matches our costs. After that, you should implement the % gradient and use the checkCostFunction routine to check% that the gradient is correct. Finally, you should implement% regularization.%% Notes: X - num_movies x num_features matrix of movie features% Theta - num_users x num_features matrix of user features% Y - num_movies x num_users matrix of user ratings of movies% R - num_movies x num_users matrix, where R(i, j) = 1 if the % i-th movie was rated by the j-th user%% You should set the following variables correctly:%% X_grad - num_movies x num_features matrix, containing the % partial derivatives w.r.t. to each element of X% Theta_grad - num_users x num_features matrix, containing the % partial derivatives w.r.t. to each element of Theta%J = (1/2).*sum(sum(((X*Theta').*R-Y.*R).^2))+(lambda./2.*sum(sum(Theta.^2)))+(lambda./2.*sum(sum(X.^2))); % Only predict rating X*Theta' if user has rated (i.e. R=1)X_grad = (((X*Theta').*R*Theta-Y.*R*Theta)+lambda.*X);Theta_grad = ((X'*((X*Theta').*R)-X'*(Y.*R)))'+lambda.*Theta;% Alternative according to exercise handout%[r,c]=size(R);%for i=1:r% idx = find(R(i,:)==1);% Theta_temp = Theta(idx,:);% Y_temp = Y(i,idx);% X_grad(i,:) = (X(i,:)*Theta_temp'-Y_temp)*Theta_temp;%end% For Theta_grad, similar approach to X_grad% =============================================================grad = [X_grad(:); Theta_grad(:)];end
2.3 Learning movie recommendations
%% ================== Part 7: Learning Movie Ratings ====================% Now, you will train the collaborative filtering model on a movie rating % dataset of 1682 movies and 943 users%fprintf('\nTraining collaborative filtering...\n');% Load dataload('ex8_movies.mat');% Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies by % 943 users%% R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a% rating to movie i% Add our own ratings to the data matrixY = [my_ratings Y];R = [(my_ratings ~= 0) R];% Normalize Ratings[Ynorm, Ymean] = normalizeRatings(Y, R);% Useful Valuesnum_users = size(Y, 2);num_movies = size(Y, 1);num_features = 10;% Set Initial Parameters (Theta, X)X = randn(num_movies, num_features);Theta = randn(num_users, num_features);initial_parameters = [X(:); Theta(:)];% Set options for fmincgoptions = optimset('GradObj', 'on', 'MaxIter', 100);% Set Regularizationlambda = 10;theta = fmincg (@(t)(cofiCostFunc(t, Ynorm, R, num_users, num_movies, ... num_features, lambda)), ... initial_parameters, options);% Unfold the returned theta back into U and WX = reshape(theta(1:num_movies*num_features), num_movies, num_features);Theta = reshape(theta(num_movies*num_features+1:end), ... num_users, num_features);fprintf('Recommender system learning completed.\n');fprintf('\nProgram paused. Press enter to continue.\n');pause;%% ================== Part 8: Recommendation for you ====================% After training the model, you can now make recommendations by computing% the predictions matrix.%p = X * Theta';my_predictions = p(:,1) + Ymean;movieList = loadMovieList();[r, ix] = sort(my_predictions, 'descend');fprintf('\nTop recommendations for you:\n');for i=1:10 j = ix(i); fprintf('Predicting rating %.1f for movie %s\n', my_predictions(j), ... movieList{j});endfprintf('\n\nOriginal ratings provided:\n');for i = 1:length(my_ratings) if my_ratings(i) > 0 fprintf('Rated %d for %s\n', my_ratings(i), ... movieList{i}); endend
- Andrew NG 机器学习 练习8-Anomaly Detection and Recommender Systems
- Andrew Ng机器学习week9(Anomaly Detection and Recommender Systems)编程习题
- Machine Learning by Andrew Ng --- Anomaly Detection and Recommender systems
- Andrew NG 机器学习 笔记-week9-异常检测和推荐系统(Anomaly Detection and Recommender Systems)
- [Coursera机器学习]Anomaly Detection and Recommender Systems WEEK9编程作业
- Programming Exercise 8:Anomaly Detection and Recommender Systems第一部分
- Programming Exercise 8:Anomaly Detection and Recommender Systems 第二部分
- Programming Exercise 8: Anomaly Detection and Recommender Systems Machine Learning
- anomaly detection ng recommender system
- Anomaly Detection and Recommender Systems[异常检测&推荐系统]
- Coursera Machine Learning 第九周 quizProgramming Exercise 8: Anomaly Detection and Recommender Systems
- Ng机器学习 Week9 Anomaly Detection
- NG机器学习week9 Anomaly Detection
- Machine Learning week 9 quiz: programming assignment-Anomaly Detection and Recommender Systems
- Andrew Ng Machine Learning 专题【Anomaly Detection】
- Andrew Ng Machine Learning 专题【Recommender Systems】
- 斯坦福NG机器学习课程:Anomaly Detection笔记
- Stanford 机器学习 Anomaly Detection
- 【剑指offer】51-67题
- 递归调用
- 第二十四天 目录和路径操作
- CNN训练Cifar-10技巧
- 算法课作业系列7——Best Time to Buy and Sell Stock with Transaction Fee
- Andrew NG 机器学习 练习8-Anomaly Detection and Recommender Systems
- 新建一个Vue项目需要做的
- js数组,循环,闭包问题
- 二叉树三种遍历(递归的妙用)
- 05_RxJava与RxAndroid
- Spring学习笔记
- AI行业者必看!领先时代的智能资讯机器人步步逼近!
- 机器学习第一章
- logback与Spring、SpringMVC结合使用教程