# Linear Regression/线性回归与正则化（Andrew Ng 机器学习 一 ）

## 关于正则化

X是矩阵，代表训练集，每一行是一个样本的各特征值。y是个向量，对应每个样本的结果值。

Normal Equation

## 附录（编程答案）

```function plotData(x, y)
% ====================== YOUR CODE HERE ======================
figure; % open a new figure window
plot(x, y, '+', 'MarkerSize', 10);
xlabel('Population of City in 10,000s');
ylabel('Profit in \$10,000s');
% ============================================================
end```
• computeCost.m
```function J = computeCost(X, y, theta)
% Initialize some useful values
m = length(y); % number of training examples
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.
J = sum((X * theta - y) .^ 2) / (2 * m);
% ==========================================================
end```
```function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
% ====================== YOUR CODE HERE ======================
theta = theta - alpha * (X' * (X * theta - y)) / m
% ============================================================
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
end```
• featureNormalize.m
```function [X_norm, mu, sigma] = featureNormalize(X)
% You need to set these values correctly
X_norm = X;
mu = zeros(1, size(X, 2));
sigma = zeros(1, size(X, 2));
% ====================== YOUR CODE HERE ======================
len = length(X);
mu = mean(X);
sigma = std(X);
X_norm = (X - ones(len, 1) * mu) ./ (ones(len, 1) * sigma);
% ============================================================
end```
• normalEqn.m
```function [theta] = normalEqn(X, y)
theta = zeros(size(X, 2), 1);
% ====================== YOUR CODE HERE ======================
% ---------------------- Sample Solution ----------------------
theta = pinv(X' * X) * X' * y
% ============================================================
end```

77 篇文章40 人订阅

0 条评论

## 相关文章

1.3K9

3726

8426

1643

### 【专知-Deeplearning4j深度学习教程03】使用多层神经网络分类MNIST数据集:图文+代码

【导读】主题链路知识是我们专知的核心功能之一，为用户提供AI领域系统性的知识学习服务，一站式学习人工智能的知识，包含人工智能（ 机器学习、自然语言处理、计算机视...

46011

4585

### 吴恩达斯坦福CS230第一名：图像超级补全，效果惊艳（附代码）

【新智元导读】图像修复（Image inpainting）是一个已经被广泛研究的计算机视觉问题，即恢复图像中缺失的部分。斯坦福大学CS230课程的Mark Sa...

1483

4286

3357

4361