日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Machine Learning week 6 quiz: programming assignment-Regularized Linear Regression and Bias/Variance

發(fā)布時間:2025/3/21 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Machine Learning week 6 quiz: programming assignment-Regularized Linear Regression and Bias/Variance 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、ex5.m

%% Machine Learning Online Class % Exercise 5 | Regularized Linear Regression and Bias-Variance % % Instructions % ------------ % % This file contains code that helps you get started on the % exercise. You will need to complete the following functions: % % linearRegCostFunction.m % learningCurve.m % validationCurve.m % % For this exercise, you will not need to change any code in this file, % or any other files other than those mentioned above. %%% Initialization clear ; close all; clc%% =========== Part 1: Loading and Visualizing Data ============= % We start the exercise by first loading and visualizing the dataset. % The following code will load the dataset into your environment and plot % the data. %% Load Training Data fprintf('Loading and Visualizing Data ...\n')% Load from ex5data1: % You will have X, y, Xval, yval, Xtest, ytest in your environment load ('ex5data1.mat');% m = Number of examples m = size(X, 1);% Plot training data plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5); xlabel('Change in water level (x)'); ylabel('Water flowing out of the dam (y)');fprintf('Program paused. Press enter to continue.\n'); pause;%% =========== Part 2: Regularized Linear Regression Cost ============= % You should now implement the cost function for regularized linear % regression. %theta = [1 ; 1]; % 2*1 J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);fprintf(['Cost at theta = [1 ; 1]: %f '...'\n(this value should be about 303.993192)\n'], J);fprintf('Program paused. Press enter to continue.\n'); pause;%% =========== Part 3: Regularized Linear Regression Gradient ============= % You should now implement the gradient for regularized linear % regression. %theta = [1 ; 1]; [J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);fprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...'\n(this value should be about [-15.303016; 598.250744])\n'], ...grad(1), grad(2));fprintf('Program paused. Press enter to continue.\n'); pause;%% =========== Part 4: Train Linear Regression ============= % Once you have implemented the cost and gradient correctly, the % trainLinearReg function will use your cost function to train % regularized linear regression. % % Write Up Note: The data is non-linear, so this will not give a great % fit. %% Train linear regression with lambda = 0 lambda = 0; [theta] = trainLinearReg([ones(m, 1) X], y, lambda);% Plot fit over the data plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5); xlabel('Change in water level (x)'); ylabel('Water flowing out of the dam (y)'); hold on; plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2) hold off;fprintf('Program paused. Press enter to continue.\n'); pause;%% =========== Part 5: Learning Curve for Linear Regression ============= % Next, you should implement the learningCurve function. % % Write Up Note: Since the model is underfitting the data, we expect to % see a graph with "high bias" -- slide 8 in ML-advice.pdf %lambda = 0; [error_train, error_val] = ...learningCurve([ones(m, 1) X], y, ...[ones(size(Xval, 1), 1) Xval], yval, ...lambda);plot(1:m, error_train, 1:m, error_val); title('Learning curve for linear regression') legend('Train', 'Cross Validation') xlabel('Number of training examples') ylabel('Error') axis([0 13 0 150])fprintf('# Training Examples\tTrain Error\tCross Validation Error\n'); for i = 1:mfprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i)); endfprintf('Program paused. Press enter to continue.\n'); pause;%% =========== Part 6: Feature Mapping for Polynomial Regression ============= % One solution to this is to use polynomial regression. You should now % complete polyFeatures to map each example into its powers %p = 8;% Map X onto Polynomial Features and Normalize X_poly = polyFeatures(X, p); [X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize X_poly = [ones(m, 1), X_poly]; % Add Ones% Map X_poly_test and normalize (using mu and sigma) X_poly_test = polyFeatures(Xtest, p); X_poly_test = bsxfun(@minus, X_poly_test, mu); X_poly_test = bsxfun(@rdivide, X_poly_test, sigma); X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones% Map X_poly_val and normalize (using mu and sigma) X_poly_val = polyFeatures(Xval, p); X_poly_val = bsxfun(@minus, X_poly_val, mu); X_poly_val = bsxfun(@rdivide, X_poly_val, sigma); X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Onesfprintf('Normalized Training Example 1:\n'); fprintf(' %f \n', X_poly(1, :));fprintf('\nProgram paused. Press enter to continue.\n'); pause;%% =========== Part 7: Learning Curve for Polynomial Regression ============= % Now, you will get to experiment with polynomial regression with multiple % values of lambda. The code below runs polynomial regression with % lambda = 0. You should try running the code with different values of % lambda to see how the fit and learning curve change. %lambda = 0; [theta] = trainLinearReg(X_poly, y, lambda);% Plot training data and fit figure(1); plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5); plotFit(min(X), max(X), mu, sigma, theta, p); xlabel('Change in water level (x)'); ylabel('Water flowing out of the dam (y)'); title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));figure(2); [error_train, error_val] = ...learningCurve(X_poly, y, X_poly_val, yval, lambda); plot(1:m, error_train, 1:m, error_val);title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda)); xlabel('Number of training examples') ylabel('Error') axis([0 13 0 100]) legend('Train', 'Cross Validation')fprintf('Polynomial Regression (lambda = %f)\n\n', lambda); fprintf('# Training Examples\tTrain Error\tCross Validation Error\n'); for i = 1:mfprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i)); endfprintf('Program paused. Press enter to continue.\n'); pause;%% =========== Part 8: Validation for Selecting Lambda ============= % You will now implement validationCurve to test various values of % lambda on a validation set. You will then use this to select the % "best" lambda value. %[lambda_vec, error_train, error_val] = ...validationCurve(X_poly, y, X_poly_val, yval);close all; plot(lambda_vec, error_train, lambda_vec, error_val); legend('Train', 'Cross Validation'); xlabel('lambda'); ylabel('Error');fprintf('lambda\t\tTrain Error\tValidation Error\n'); for i = 1:length(lambda_vec)fprintf(' %f\t%f\t%f\n', ...lambda_vec(i), error_train(i), error_val(i)); endfprintf('Program paused. Press enter to continue.\n'); pause;

二、linearRegCostFunction.m

function [J, grad] = linearRegCostFunction(X, y, theta, lambda) %LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear %regression with multiple variables % [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the % cost of using theta as the parameter for linear regression to fit the % data points in X and y. Returns the cost in J and the gradient in grad% Initialize some useful values m = length(y); % number of training examples % m% You need to return the following variables correctly J = 0; % 1*1 grad = zeros(size(theta));% ====================== YOUR CODE HERE ====================== % Instructions: Compute the cost and gradient of regularized linear % regression for a particular choice of theta. % % You should set J to the cost and grad to the gradient. %% linearRegh = X * theta; % m*(n+1) × (n+1)* -> m* J_part1 = sum((h-y).^2) /2 /m;theta2 = theta(2:end, :); J_part2 = sum(theta2.^2)/2/m*lambda;J = J_part1 + J_part2;% gradient grad_ori = X' * (h-y) / m; %(n+1)*m × m*1 -> (n+1)*1 grad(1) = grad_ori(1); grad(2:end) = grad_ori(2:end) + lambda/m*theta(2:end);% =========================================================================grad = grad(:);end

三、learningCurve.m

function [error_train, error_val] = ...learningCurve(X, y, Xval, yval, lambda) %LEARNINGCURVE Generates the train and cross validation set errors needed %to plot a learning curve % [error_train, error_val] = ... % LEARNINGCURVE(X, y, Xval, yval, lambda) returns the train and % cross validation set errors for a learning curve. In particular, % it returns two vectors of the same length - error_train and % error_val. Then, error_train(i) contains the training error for % i examples (and similarly for error_val(i)). % % In this function, you will compute the train and test errors for % dataset sizes from 1 up to m. In practice, when working with larger % datasets, you might want to do this in larger intervals. %% Number of training examples m = size(X, 1); % m% You need to return these values correctly error_train = zeros(m, 1); % m*1 error_val = zeros(m, 1); % m*1% ====================== YOUR CODE HERE ====================== % Instructions: Fill in this function to return training errors in % error_train and the cross validation errors in error_val. % i.e., error_train(i) and % error_val(i) should give you the errors % obtained after training on i examples. % % Note: You should evaluate the training error on the first i training % examples (i.e., X(1:i, :) and y(1:i)). % % For the cross-validation error, you should instead evaluate on % the _entire_ cross validation set (Xval and yval). % % Note: If you are using your cost function (linearRegCostFunction) % to compute the training and cross validation error, you should % call the function with the lambda argument set to 0. % Do note that you will still need to use lambda when running % the training to obtain the theta parameters. % % Hint: You can loop over the examples with the following: % % for i = 1:m % % Compute train/cross validation errors using training examples % % X(1:i, :) and y(1:i), storing the result in % % error_train(i) and error_val(i) % .... % % end %% ---------------------- Sample Solution ----------------------for i = 1:mX_train = X(1:i, :); y_train = y(1:i);[theta] = trainLinearReg(X_train, y_train, lambda); lambda0 = 0;[J_train grad_train] = linearRegCostFunction(X_train, y_train, theta, lambda0); [J_val grad_val] = linearRegCostFunction(Xval, yval, theta, lambda0);error_train(i) = J_train; error_val(i) = J_val;end% -------------------------------------------------------------% =========================================================================end


四、validationCurve.m

function [lambda_vec, error_train, error_val] = ...validationCurve(X, y, Xval, yval) %VALIDATIONCURVE Generate the train and validation errors needed to %plot a validation curve that we can use to select lambda % [lambda_vec, error_train, error_val] = ... % VALIDATIONCURVE(X, y, Xval, yval) returns the train % and validation errors (in error_train, error_val) % for different values of lambda. You are given the training set (X, % y) and validation set (Xval, yval). %% Selected values of lambda (you should not change this) lambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';% You need to return these variables correctly. error_train = zeros(length(lambda_vec), 1); error_val = zeros(length(lambda_vec), 1);% ====================== YOUR CODE HERE ====================== % Instructions: Fill in this function to return training errors in % error_train and the validation errors in error_val. The % vector lambda_vec contains the different lambda parameters % to use for each calculation of the errors, i.e, % error_train(i), and error_val(i) should give % you the errors obtained after training with % lambda = lambda_vec(i) % % Note: You can loop over lambda_vec with the following: % % for i = 1:length(lambda_vec) % lambda = lambda_vec(i); % % Compute train / val errors when training linear % % regression with regularization parameter lambda % % You should store the result in error_train(i) % % and error_val(i) % .... % % end % %for i = 1:length(lambda_vec) lambda = lambda_vec(i); [theta] = trainLinearReg(X, y, lambda); lambda0 = 0; [J_train grad_train] = linearRegCostFunction(X, y, theta, lambda0); [J_val grad_val] = linearRegCostFunction(Xval, yval, theta, lambda0);error_train(i) = J_train; error_val(i) = J_val; end% =========================================================================end

五、polyFeatures.m

function [X_poly] = polyFeatures(X, p) %POLYFEATURES Maps X (1D vector) into the p-th power % [X_poly] = POLYFEATURES(X, p) takes a data matrix X (size m x 1) and % maps each example into its polynomial features where % X_poly(i, :) = [X(i) X(i).^2 X(i).^3 ... X(i).^p]; %% You need to return the following variables correctly. X_poly = zeros(numel(X), p); % m*p% ====================== YOUR CODE HERE ====================== % Instructions: Given a vector X, return a matrix X_poly where the p-th % column of X contains the values of X to the p-th power. % % m = numel(X); for i = 1:m for j = 1:p X_poly(i, j) = X(i).^j; end end% =========================================================================end

六、submit results


總結(jié)

以上是生活随笔為你收集整理的Machine Learning week 6 quiz: programming assignment-Regularized Linear Regression and Bias/Variance的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 在线观看91视频 | 超碰自拍 | 黄网在线看 | 少妇特黄一区二区三区 | 桃色在线观看 | 超在线视频| 伊人久久国产精品 | 视色网 | 高潮一区 | 日韩精品一区在线视频 | 伊人亚洲 | 国产乱淫av一区二区三区 | 国产香蕉视频 | 天天干妹子 | 男人懂的网站 | 驯服少爷漫画免费观看下拉式漫画 | 性欧美大战久久久久久久 | 18性xxxxx性猛交 | 色噜噜网站 | 女儿的朋友5中汉字晋通话 欧美成人免费高清视频 | 538在线精品| 天堂久久久久久 | 亚洲一区二区三区高清视频 | 超碰五月| 老熟女重囗味hdxx69 | 日本熟妇毛茸茸丰满 | 性生交大片免费看l | 国产精品久久久久久久久免费相片 | 视频一区在线播放 | 欧美大尺度床戏做爰 | 国产剧情久久 | 亚洲国产精品成人无久久精品 | 可以免费看的av毛片 | 啪啪福利社 | 丰满人妻一区二区三区性色 | 欧美视频在线观看视频 | 女人18岁毛片 | 香蕉视频亚洲一级 | 一区二区三区成人 | 日韩美av| 色老久久 | 亚洲国内自拍 | 亚洲午夜久久久久久久久 | 欧美另类z0zx974 | 日韩视频一区二区 | 自拍偷拍国产视频 | 黄色天堂 | 国产精品久久av无码一区二区 | 国产一区二区波多野结衣 | 色噜| 人乳喂奶hd无中字 | 夜夜操夜夜| 久久福利网站 | 欧美成人三级在线播放 | 国产a免费视频 | 精品久久伊人 | 国产毛片aaa | 99欧美| 熟女少妇一区二区三区 | 天天操穴 | www.xxxxx日本| 免费无码国产v片在线观看 三级全黄做爰在线观看 | 国产超91| 蜜桃av鲁一鲁一鲁一鲁俄罗斯的 | 成年人黄色网址 | 国产男女av | 久久国产热视频 | 国产91在线免费 | 可以直接看的毛片 | 久久亚洲成人av | 看免费一级片 | 国产尤物视频 | 少妇的被肉日常np | av不卡在线观看 | 久久久久亚洲av成人人电影 | 欧美一区二区三区成人久久片 | 朱竹清到爽高潮痉挛 | 成人在线激情视频 | 国产大奶在线 | 玖玖视频在线 | 福利在线小视频 | 欧美一区二区在线观看视频 | 视频三区在线 | 亚洲伦理在线视频 | 麻豆蜜桃wwww精品无码 | 日韩欧美亚洲天堂 | 女教师三上悠亚ssni-152 | av天天色| 2级黄色片 | 国产 日韩 欧美 综合 | 香蕉久久久久久久av网站 | 尤物视频在线免费观看 | 亚洲第一视频网站 | 亚洲国产网址 | 老鸭窝av在线 | 成人在线免费视频 | 久久午夜精品人妻一区二区三区 | 免费观看一区二区三区 | 一级黄色大片在线观看 |