线性代数作业




 

 

 

 

 

 

 

 

 

 

#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke

import numpy as np  
import matplotlib.pyplot as plt  
from solutions_3 import *

# 产生一个方波(x,y)
x = np.linspace(-10,10,300) 
y=[]
for i in np.cos(x):
    if i>0:
        y.append(0)
    else:
        y.append(2)
y=np.array(y)

# write Your code, Fourier function    
plt.plot(x,y,color='g',label='origin') 
plt.plot(x,fourier(x,y,3),color='r',label='3')
plt.plot(x,fourier(x,y,8),color='b',label='8')
plt.plot(x,fourier(x,y,23),color='k',label='23')

plt.legend()
plt.axis('equal')
plt.show()

  

 

 

#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke

import numpy as np  
import matplotlib.pyplot as plt  
from solutions_3 import *

A=np.array([[3,1],[2,4]])/4.0

# write Your code
# def eigshow(A):

eigshow(A)

 

 

 

 

 

 

 

PCA

 

 

#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke

import numpy as np
import matplotlib.pyplot as plt  

def pca(dataMat, topNfeat=5):  
    meanVals = np.mean(dataMat, axis=0)  
    meanRemoved = dataMat - meanVals                #减去均值  
    covMat = meanRemoved.T.dot(meanRemoved)         #求协方差方阵  
    eigVals, eigVects = np.linalg.eig(covMat)       #求特征值和特征向量  
    eigValInd = np.argsort(eigVals)                 #对特征值进行排序  
    eigValInd = eigValInd[:-(topNfeat + 1):-1]    
    redEigVects = eigVects[:, eigValInd]            #除去不需要的特征向量  
    lowDDataMat = meanRemoved.dot(redEigVects)      #求新的数据矩阵  
    reconMat = (lowDDataMat.dot(redEigVects.T)) + meanVals  
    reduceData = lowDDataMat + np.mean(dataMat)

    return reduceData,reconMat  
    
N=100
x=np.linspace(2,4,N)
y=x*2-4

x1=x+(np.random.rand(N)-0.5)*1.5
y1=y+(np.random.rand(N)-0.5)*1.5

data = np.array([x1,y1])
a,b=pca(data.T,1)

plt.plot(x,y,color='g',linestyle='-',marker='',label='ideal') 
plt.plot(x1,y1,color='b',linestyle='',marker='o',label='noise')
plt.plot(b[:,0],b[:,1],color='r',linestyle='',marker='>',label='recon')
plt.plot(a[:,0],np.zeros(N),color='k',linestyle='',marker='*',label='lowD')

plt.legend()
plt.axis('equal')

plt.show()

 

 

 

SVD

#!/usr/bin/python
# -*- coding: utf-8 -*
# Copy Right by heibanke

import numpy as np
from matplotlib import pyplot as plt

A=np.array([[-0.2,-1],[1.1,0.5]])
U,s,V=np.linalg.svd(A)

# S=np.array([[s[0],0],[0,s[1]]])
# modified by conkang
S=np.diag(s)

fig = plt.figure()
ax0 = fig.add_subplot(221)
ax1 = fig.add_subplot(222)
ax2 = fig.add_subplot(223)
ax3 = fig.add_subplot(224)

def plot_2D_mat(M,ax,text=""):
    ax.plot([0,M[0,0]],[0,M[1,0]],'b-o')
    ax.plot([0,M[0,1]],[0,M[1,1]],'r-o')
    ax.set_title(text)
    ax.axis('equal')
    ax.set_xlim([-1.5,1.5])
    ax.set_ylim([-1.5,1.5])
    ax.grid(True)
    

plot_2D_mat(np.eye(2),ax0,"origin")
plot_2D_mat(A,ax1,"A (USV) Matrix")
plot_2D_mat(V.T,ax2,"V Matrix")
plot_2D_mat(S.dot(V.T),ax3,"SV Matrix")

plt.show()

 https://pan.baidu.com/s/1gfMX6h1

posted @ 2017-12-05 22:28  HugoLester  阅读(351)  评论(0编辑  收藏  举报