欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Introduction to Python Exercises 11.Matplotlib

程序员文章站 2022-07-14 10:05:55
...

【问题解决】

Introduction to Python Exercises 11.Matplotlib

import numpy as np
import matplotlib.pyplot as plt 
# import math

x = np.linspace(0, 2, 30)  # 创建X轴的数值,在0和2之间产生30个均匀分布的值  
# y = [math.pow(math.sin(xi - 2), 2) * math.exp(-math.pow(xi, 2)) for xi in x]
y = np.power(np.sin(x - 2), 2) * np.exp(-np.power(x, 2))

plt.plot(x, y)      # 调用plot函数,这并不会立即显示函数图像 
plt.xlabel('x')     # 使用xlabel函数添加X轴的标签 
plt.ylabel('f(x)')  # 使用ylabel函数添加y轴的标签  
plt.title('f(x) = sin^2(x-2)*e^(-x^2)') # 标题

plt.show()          # 调用show函数显示函数图像 

效果图示:

Introduction to Python Exercises 11.Matplotlib


Introduction to Python Exercises 11.Matplotlib

题目的意思应该是用最小二乘法求解参数b的预测值,可使用函数numpy.linalg.lstsq(具体的参数与返回值可参考网址https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq

import matplotlib.pyplot as plt
import numpy as np

X = np.random.random((20, 10))  # 元素为[0.0, 1.0)的浮点数的20*10矩阵
b = np.random.randn(10, 1)      # 元素服从标准正态分布的向量
z = np.random.random((20, 1))   # 元素为[0.0, 1.0)的浮点数的向量
Y = np.dot(X, b) + z
b_hat = np.array(np.linalg.lstsq(X, Y, rcond = -1)[0])  # 线性回归的第一个参数

x = np.arange(0, 10)
plt.scatter(x, b, c = 'r', marker = 'x', label = '$true coefficients$')
plt.scatter(x, b_hat, c = 'b', marker = 'o', label = '$estimated coefficients$')
plt.xlabel('index')
plt.ylabel('value')
plt.legend()  
plt.show()

效果图示:

Introduction to Python Exercises 11.Matplotlib


Introduction to Python Exercises 11.Matplotlib

高斯核密度估计函数scipy.stats.gaussian_kde可参考网址https://github.com/scipy/scipy/blob/master/scipy/stats/kde.py

import numpy as np  
import matplotlib.pyplot as plt  
import scipy.stats  
  
# generate a vector z of 10000 observations from standard normal distribution.   
z = np.random.normal(loc = 0, scale = 5.0, size = 10000) 
  
# show a histogram of z (with 25 bins)  
plt.hist(z , bins = 25, density = True, color = 'b')  
  
# use a Gaussian kernel density estimator 
kernel = scipy.stats.gaussian_kde(z)  
# obtain the PDF (kernel is a function!)  
  
x = np.linspace(-20, 20, 10000)  
plt.plot(x, kernel(x), 'r')  
  
plt.show()  

效果图示:

Introduction to Python Exercises 11.Matplotlib