jupyter代码1.数据读取及处理 2.特征归一化 3.计算协方差矩阵Sigma = □1/m∑_i=0^m▒(x^(i))(x^(i))^T 4.奇异值分解[U, S, V] = svd(Sigma) 5.Ureduce = U(:, 1:k) 6. z = Ureduceʼ * x
时间: 2024-03-03 16:48:06 浏览: 69
好的,以下是jupyter代码实现:
1. 数据读取及处理:
```python
import numpy as np
import pandas as pd
# 读取数据
data = pd.read_csv('data.csv')
# 将数据转换为numpy数组
X = data.values
# 将特征值和目标值分开
x = X[:, :-1]
y = X[:, -1]
```
2. 特征归一化:
```python
# 特征归一化
def featureNormalize(X):
# 每一列的均值
mu = np.mean(X, axis=0)
# 每一列的标准差
sigma = np.std(X, axis=0, ddof=1)
# 对每一列进行归一化处理
X_norm = (X - mu) / sigma
return X_norm, mu, sigma
# 对特征值进行归一化处理
x_norm, mu, sigma = featureNormalize(x)
```
3. 计算协方差矩阵Sigma = □1/m∑_i=0^m▒(x^(i))(x^(i))^T:
```python
# 计算协方差矩阵
Sigma = (1 / len(x_norm)) * np.dot(x_norm.T, x_norm)
```
4. 奇异值分解[U, S, V] = svd(Sigma):
```python
# 奇异值分解
U, S, V = np.linalg.svd(Sigma)
```
5. Ureduce = U[:, 1:k]:
```python
# 选取前k个特征向量构成降维矩阵
k = 2
Ureduce = U[:, :k]
```
6. z = Ureduceʼ * x:
```python
# 对样本进行降维
z = np.dot(x_norm, Ureduce)
```
阅读全文