首页 > 其他分享 >第七章

第七章

时间:2024-11-16 22:29:48浏览次数:1  
标签:plt fit observed 第七章 popt np import

7.3
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

from scipy.interpolate import CubicSpline, interp1d
import scipy.integrate as si

t = np.arange(700, 800, 20)
v = np.array([0.0977, 0.1218, 0.1406, 0.1551, 0.1664])

f = interp1d(t, v, kind="linear")

v1 = f([750, 770])
print('线性插值:', v1)

cs = CubicSpline(t, v)

v2 = cs([750, 770])
print('三次样条插值:', v2)

plt.figure(dpi=600, figsize=(7, 4))
plt.plot(t, v, '*-')
plt.plot(t, cs(t))
plt.legend(['线性插值', '三次样条插值'])
结果

7.4
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
from numpy.random import uniform

def f(x, y):
return (x ** 2 - 2 * x) * np.exp(x ** 2 * y ** 2 - 9)

num_points = 100
x_random = uniform(-3, 3, num_points)
y_random = uniform(-4, 4, num_points)

z_random = f(x_random, y_random)

grid_x, grid_y = np.mgrid[-3:3:100j, -4:4:100j]

grid_z = griddata((x_random, y_random), z_random, (grid_x, grid_y), method='cubic')

plt.contourf(grid_x, grid_y, grid_z, levels=20)
plt.colorbar()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interpolation Result of f(x,y)')
plt.show()
结果

7.7
(1)import numpy as np
from scipy.optimize import curve_fit

def g(x, a, b):
return 10 * a / (10 * b + (a - 10 * b) * np.exp(-a * np.sin(x)))

a = 1.1
b = 0.01
x_observed = np.arange(1, 21)
y_observed = g(x_observed, a, b)

popt, pcov = curve_fit(g, x_observed, y_observed)

print("拟合得到的参数a:", popt[0])
print("拟合得到的参数b:", popt[1])
结果

(2)import numpy as np
from scipy.optimize import leastsq

def g(x, a, b):
return 10 * a / (10 * b + (a - 10 * b) * np.exp(-a * np.sin(x)))

a = 1.1
b = 0.01

x_observed = np.arange(1, 21)
y_observed = g(x_observed, a, b)

def error_function(params, x, y):
a_fit, b_fit = params
y_fit = g(x, a_fit, b_fit)
return y - y_fit

initial_guess = (1.0, 0.01)

popt, pcov = leastsq(error_function, initial_guess, args=(x_observed, y_observed))

print("拟合得到的参数a:", popt[0])
print("拟合得到的参数b:", popt[1])
结果

(3)import numpy as np
from scipy.optimize import least_squares

def g(x, a, b):
return 10 * a / (10 * b + (a - 10 * b) * np.exp(-a * np.sin(x)))

a = 1.1
b = 0.01

x_observed = np.arange(1, 21)
y_observed = g(x_observed, a, b)

def error_function(params, x, y):
a_fit, b_fit = params
y_fit = g(x, a_fit, b_fit)
return y - y_fit

initial_guess = (1.0, 0.01)

result= least_squares(error_function, initial_guess, args=(x_observed, y_observed))
popt = result.x

print("拟合得到的参数a:", popt[0])
print("拟合得到的参数b:", popt[1])
结果

7.10
(1)
import numpy as np
from scipy.interpolate import lagrange, interp1d, CubicSpline
import matplotlib.pyplot as plt

x0 = np.arange(-2, 5, 0.3)[:, np.newaxis]
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])[:, np.newaxis]

x = np.linspace(-2, 4.9, 100)[:, np.newaxis]

y1 = lagrange(x0.flatten(), y0.flatten())(x.flatten()).reshape(-1, 1)
y2 = interp1d(x0.flatten(), y0.flatten())(x.flatten()).reshape(-1, 1)
y3 = CubicSpline(x0.flatten(), y0.flatten())(x.flatten()).reshape(-1, 1)
plt.subplot(131)
plt.plot(x, y1)
plt.title('拉格朗日插值')

plt.scatter(x0, y0, c='r', marker='o', label='原始数据点')
plt.xlabel('自变量')
plt.ylabel('因变量')
plt.legend(['拉格朗日插值', '原始数据点'])
plt.subplot(132)
plt.plot(x, y2)

plt.title('分段线性插值')

plt.scatter(x0, y0, c='r', marker='o')

plt.xlabel('自变量')

plt.ylabel('因变量')

plt.legend(['分段线性插值', '原始数据点'])

plt.subplot(133)
plt.plot(x, y3)

plt.title('三次样条插值')

plt.scatter(x0, y0, c='r', marker='o')

plt.xlabel('自变量')

plt.ylabel('因变量')

plt.legend(['三次样条插值', '原始数据点'])

plt.show()
结果

7.10
(2)import numpy as np
from scipy.optimize import curve_fit

x0 = np.arange(-2, 5, 0.3)[:, np.newaxis]
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])[:, np.newaxis]

x = np.linspace(-2, 4.9, 100)[:, np.newaxis]

def polynomial_fit(x, y, degree):

def polynomial_function(x, *params):
    return np.polyval(params, x)
popt, pcov = curve_fit(polynomial_function, x.flatten(), y.flatten(), p0=np.ones(degree + 1))

fx = lambda x: polynomial_function(x, *popt)

mse = np.mean((y.flatten() - fx(x.flatten())) ** 2)
rmse = np.sqrt(mse)

return fx, popt, rmse

best_rmse = float('inf')
best_degree = None
best_fit_params = None

for degree in range(1, 10):
fx, fit_params, rmse = polynomial_fit(x0, y0, degree)

if rmse < best_rmse:
    best_rmse = rmse
    best_degree = degree
    best_fit_params = fit_params

print(f"选择的多项式阶次: {best_degree}")
print(f"多项式系数: {best_fit_params}")
print(f"剩余标准差(RMSE): {best_rmse}")
结果

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

x0 = np.arange(-2, 5, 0.3)[:, np.newaxis]
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])[:, np.newaxis]

x = np.linspace(-2, 4.9, 100)[:, np.newaxis]

def normal_distribution(x, mu, s):

return 1 / (np.sqrt(2 * np.pi) * s) * np.exp(-(x - mu) ** 2 / (2 * s ** 2))

popt, pcov = curve_fit(normal_distribution, x0.flatten(), y0.flatten(), p0=np.random.rand(1, 2))

f = lambda x: normal_distribution(x, popt[0], popt[1])

plt.subplot(111)
plt.plot(x, f(x))
plt.title('拟合的正态分布密度函数')

plt.show()
结果

标签:plt,fit,observed,第七章,popt,np,import
From: https://www.cnblogs.com/111q/p/18549998

相关文章

  • 第七章课后习题
    习题7.1点击查看代码importnumpyasnpfromscipy.interpolateimportinterp1dfromscipy.integrateimportquadimportmatplotlib.pyplotaspltg=lambdax:(3*x**2+4*x+6)*np.sin(x)/(x**2+8*x+6)x0=np.linspace(0,10,1000)y0=g(x0......
  • 第七章 利用CSS和多媒体美化页面
    7.1CSS链接的美化        在HTML5中,<a></a>标签始终定义超链接,用于从一张页面链接到另一张页面。<a>元素最重要的属性是href属性,它指示链接的目标,如果未设置href属性,后续多个属性均无法使用,则只是超链接的占位符。在谷歌浏览器中,鼠标悬停链接时无明显效果。  ......
  • 【教程】第七章:工作流——自动赋能,效率飞跃
    恭喜你走到了这最后一章!我们将在这一章中介绍和简单探索NocoBase的强大工作流功能。通过这个功能,你可以为系统中的任务自动化操作,节省时间并提升效率。上节挑战答案但在开始之前,先回顾一下上节的挑战吧!我们成功地为“伙伴”角色配置了评论权限,如下:添加权限:允许用户发布评论......
  • 第七章
    7.1在区间[0,10]上等间距取1000个点Xi(i为下标,i=1,2,3,...,1000),并计算在这些点Xi处函数g(x)=((3x2+4x+6)sinx)/(x2+8x+6)的函数值yi(i为下标),利用观测点(Xi,Yi)(i=1,2,3,...,1000),求三次样条插值函数h(x),并求积分g(x)从0到10和h(x)从0到10。点击查看代码importscipy.interpolate......
  • 第七章-输入和输出流
    一、单项选择题1.File对象不能用来                                                   【】A.命名文件          B.查询文件属性          C.读写文件        D.处理目录2.......
  • 第七章:IDEA集成Git
    目录一、环境准备1.配置Git忽略文件2.定位Git程序二、初始化本地库三、添加暂存区四、提交本地库五、切换版本六、分支操作1.创建分支2.切换分支3.删除分支七、合并分支1.正常合并2.冲突合并总结一、环境准备1.配置Git忽略文件我们再写代码的时候,系统常常会......
  • 第七章课后练习题二
    用表格布局页面,利用CSS技术,及添加多媒体,制作并美化“心灵之音”页面。代码及运行结果如下:<!DOCTYPEhtml><html> <head> <metacharset="utf-8"> <title>心灵之音</title> <styletype="text/css"> body{ background-image:url(img......
  • 第七章 利用CSS和多媒体美化页面
    7.1CSS链接美化7.1.1.文字链接的美化在HTML5中,<a></a>标签始终定义超链接,用于从一张页面链接到另一张页面,<a>元素最重要的属性是href属性,它指示链接的目标,如果未设置href属性,后续多个属性均无法使用,则只是超链接的占位符。在谷歌浏览器中,鼠标悬停链接时无明显效果。设计......
  • 第七章作业2
    <!DOCTYPEhtml><html> <head> <metacharset="utf-8"> <title>心灵之音</title> <styletype="text/css"> div{ width:900px; height:820px; border:1pxsolid; background-image:......
  • 第七章利用CSS和多媒体美化页面
    通过对网页中元素、布局和色彩的合理设计,可以使网页达到较好的视觉效果。网页中常用超链接、列表和表格等网页元素,所以,对这些元素进行美化,可以大大提高网站的质量。尤其是多媒体元素的加入,使网页更加丰富多彩。7.1CSS链接的美化在前面的章节中,已经学习了超链接的简单知识......