《NumPy Beginner's Guide》笔记Chapter6

# -*- coding: utf-8 -*-

__author__ = 'ZengDong'
#日期 = 18:28

import numpy as np
""" 1. Linear algebra Linear algebra is an important branch of mathematics. The numpy.linalg package contains linear algebra functions. function: np.linalg.inv(A) A * inverse """
#create the matrix with the mat function
A =np.mat("0 1 2; 1 0 3; 4 -3 8")
print("A \n", A)

#inv function : invert the matrix
inverse = np.linalg.inv(A)
print("inverse of A\n", inverse)

""" 输出: ('A \n', matrix([[ 0, 1, 2], [ 1, 0, 3], [ 4, -3, 8]])) ('inverse of A\n', matrix([[-4.5, 7. , -1.5], [-2. , 4. , -1. ], [ 1.5, -2. , 0.5]])) """

#验证
print(np.dot(np.linalg.inv(A), A))
print(A * inverse)



""" 2. Solving linear systems A matrix transforms a vector into another vector in a linear way. This transformation mathematically corresponds to a system of linear equations. function: np.linalg.inv(A) A * inverse solve """

#create the matrixs A and b
A = np.mat("1 -2 1; 0 2 -8; -4 5 9")
print("A\n", A)
b = np.array([0, 8, -9])
print("b\n", b)
""" ('A\n', matrix([[ 1, -2, 1], [ 0, 2, -8], [-4, 5, 9]])) ('b\n', array([ 0, 8, -9])) """

#solve the linear system by calling the solve function
x = np.linalg.solve(A, b)
print("solution:", x)   #('solution:', array([ 29., 16., 3.]))




""" 3. Finding eigenvalues and eigenvectors The eig function returns a tuple containing eigenvalues and eigenvectors. function: eigvals eig """
#create a matrix as follows:
A = np.mat("3 -2; 1 0")
print("A\n", A)

#calculate eigenvalues by calling the eig function.
print("Eigenvalues", np.linalg.eigvals(A))   #('Eigenvalues', array([ 2., 1.]))

#Determine eigenvalues and eigenvectors with the eig function
#the second element contains corresponding Eigenvectors, arranged column-wise
eigenvalues, eigenvectors = np.linalg.eig(A)
print("First tuple of eig", eigenvalues)
print("Second tuple of eig\n", eigenvectors)
""" 输出: ('First tuple of eig', array([ 2., 1.])) ('Second tuple of eig\n', matrix([[ 0.89442719, 0.70710678], [ 0.4472136 , 0.70710678]])) """

#验证:Q.T*A*Q 是否 == lamda
print(np.linalg.inv(eigenvectors) * A * eigenvectors)
#输出:
""" [[ 2.00000000e+00 0.00000000e+00] [ -2.22044605e-16 1.00000000e+00]] """



""" 4. Singular value decomposition Singular value decomposition is a type of factorization that decomposes a matrix into a product of three matrices. The singular value decomposition is a generalization of the previously discussed eigenvalue decomposition. The svd function in the numpy.linalg package can perform this decomposition. function: svd diag """
#create a matrix as follows;
A = np.mat("4 11 14; 8 7 -2")
print("A\n", A)

U, Sigma, V = np.linalg.svd(A, full_matrices=False)
print("U", U)
print("Sigma", Sigma)
print("V", V)
""" ('U', matrix([[-0.9486833 , -0.31622777], [-0.31622777, 0.9486833 ]])) ('Sigma', array([ 18.97366596, 9.48683298])) ('V', matrix([[-0.33333333, -0.66666667, -0.66666667], [ 0.66666667, 0.33333333, -0.66666667]])) """

#We can form the middle matrix with the diag function
print("Product\n", U * np.diag(Sigma) * V)
""" 输出: ('Product\n', matrix([[ 4., 11., 14.], [ 8., 7., -2.]])) """



""" 5. Pseudoinverse The inv function only accepts square matrices; the pinv function does not have this restriction. function: inv VS pinv """
#create a matrix
A = np.mat("4 11 14; 8 7 -2")
print("A\n", A)

#calculate the pseudoinverse matrix with the pinv function
pseudoinv = np.linalg.pinv(A)
print("Pseudo inverse\n", pseudoinv)
#multiply the original and pseudoinverse matrix
print("Check", A * pseudoinv)

""" 输出: ('Pseudo inverse\n', matrix([[-0.00555556, 0.07222222], [ 0.02222222, 0.04444444], [ 0.05555556, -0.05555556]])) ('Check', matrix([[ 1.00000000e+00, -8.88178420e-16], [ -1.80411242e-16, 1.00000000e+00]])) """



""" 6. Determinants The determinant is a value associated with a square matrix. The numpy.linalg module has a det function that returns the determinant of a matrix. function: det """
#create the matrix
A = np.mat("3 4; 5 6")
print("A\n", A)

#computer the determinant with the det function
print("Determinant", np.linalg.det(A))




""" 7. Fast Fourier transform function: fft ifft """
import matplotlib.pyplot as plt

#create a cosine wave with 30 points
x = np.linspace(0, 2 * np.pi, 30)
wave = np.cos(x)

#transform the cosine wave with the fft function
transformed = np.fft.fft(wave)

#apply the inverse transform with the ifft function
print(np.all(np.abs(np.fft.ifft(transformed) - wave) < 10 ** -9))

#plot
plt.plot(transformed)
#plt.show()




""" 8. Shifting The fftshift function of the numpy.linalg module shifts zero-frequency components to the center of a spectrum. The ifftshift function reverses this operation. function: fftshift """
#create a cosine wave with 30 points
x = np.linspace(0, 2 * np.pi, 30)
wave = np.cos(x)

#transform the cosine wave with the fft function
transformed = np.fft.fft(wave)

#shift the signal with the fftshift function
shifted = np.fft.fftshift(transformed)

#reverse the shift with the ifftshift function
print(np.all((np.fft.ifftshift(shifted) - transformed) < 10 ** -9))


plt.clf()
plt.plot(transformed, lw = 2)
plt.plot(shifted, lw = 3)
#plt.show()




""" 9. Random numbers Random numbers are used in Monte Carlo methods, stochastic calculus, and more. Real random numbers are hard to generate, so in practice we use pseudo random numbers. The core random number generator is based on the Mersenne Twister algorithm. function: binomial """
#initialize an array
#The binomial distribution models the number of successes in an integer number of
#independent trials of an experiment, where the probability of success in each experiment
# is a fixed number.
#测试len(cash)次数,每次服从n=9,p=0.5的binomial分布(二项分布)
cash = np.zeros(10000)
cash[0] = 1000
outcome = np.random.binomial(9, 0.5, size=len(cash))

#go through the outcomes of the coin flips and update the cash array
#玩10000次,输了减去1,赢了+1
for i in range(1, len(cash)):
    if outcome[i] < 5:
        cash[i] = cash[i - 1] - 1
    elif outcome[i] < 10:
        cash[i] = cash[i - 1] + 1
    else:
        raise AssertionError("Unexpected outcome" + outcome)
print(outcome.min(), outcome.max())



#plot
plt.clf()
plt.plot(np.arange(len(cash)), cash)
#plt.show()

#运行了好几次,有时候最后赢了,有时候最后输了





""" 10. Hypergeometric distribution function: hypergeometric """
#Initialize the outcome of the game with the hypergeometric function. The first
#parameter of this function is the number of ways to make a good selection, the
#second parameter is the number of ways to make a bad selection, and the third
#parameter is the number of items sampled.

points = np.zeros(100)
outcomes = np.random.hypergeometric(25, 1, 3, size=len(points))

#set the scores based on the outcomes from the previous step
for i in range(len(points)):
    if outcomes[i] == 3:
        points[i] = points[i - 1] + 1
    elif outcomes[i] == 2:
        points[i] = points[i - 1] - 6
    else:
        print(outcomes[i])


#plot
plt.clf()
plt.plot(np.arange(len(points)), points)
#plt.show()






""" 11. Continuous distributions Continuous distributions are modeled by the probability density functions (pdf). continuous distributions—beta, chisquare, exponential, f, gamma, gumbel, laplace, lognormal, logistic, multivariate_normal, noncentral_chisquare, noncentral_f, normal, and others. function: normal plt.hist """
#generate random numbers for a given sample size using the normal function
N = 10000
normal_values = np.random.normal(size=N)

#draw the histogram
plt.clf()
dummy, bins, dummy =plt.hist(normal_values, np.sqrt(N), normed=True, lw=1)
sigma = 1
mu = 0
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp(- (bins - mu) **2 / (2*sigma**2)), lw = 2)
#plt.show()



""" 12. Lognormal distribution A lognormal distribution is a distribution of a variable whose natural logarithm is normally distributed. The lognormal function of the random NumPy module models this distribution. function: lognormal """
#generate random numbers
N = 10000
lognormal_values = np.random.lognormal(size=N)
plt.clf()
#draw
dummy, bins, dummy = plt.hist(lognormal_values, np.sqrt(N), normed=True, lw=1)

plt.show()



sigma = 1
mu = 0
x = np.linspace(min(bins), max(bins), len(bins))
pdf = np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))/ (x * sigma * np.sqrt(2 * np.pi))
plt.plot(x, pdf,lw=3)

plt.show()








































































你可能感兴趣的:(numpy)