python如何拟合曲线图

在Python中,我们可以使用多种库来拟合曲线图,其中最常用的是Scikitlearn和NumPy,下面将详细介绍如何使用这两个库进行曲线拟合。

python如何拟合曲线图
(图片来源网络,侵删)

1、安装所需库

我们需要安装Scikitlearn和NumPy库,可以使用以下命令进行安装:

pip install scikitlearn numpy

2、准备数据

在进行曲线拟合之前,我们需要准备一些数据,这里我们使用一个简单的例子,假设我们有一组x和y的数据,我们想要找到一条曲线来拟合这些数据。

import numpy as np
import matplotlib.pyplot as plt
生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.5, 100)
绘制原始数据
plt.scatter(x, y, label='原始数据')
plt.legend()
plt.show()

3、使用Scikitlearn进行曲线拟合

Scikitlearn提供了多种回归模型,如线性回归、多项式回归、岭回归等,下面我们以线性回归为例,介绍如何使用Scikitlearn进行曲线拟合。

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
创建线性回归模型
model = LinearRegression()
拟合数据
model.fit(x.reshape(1, 1), y)
预测数据
y_pred = model.predict(x.reshape(1, 1))
计算均方误差
mse = mean_squared_error(y, y_pred)
print('均方误差:', mse)

4、可视化拟合结果

我们可以使用matplotlib库将拟合结果可视化,以下是完整的代码:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.5, 100)
创建线性回归模型
model = LinearRegression()
拟合数据
model.fit(x.reshape(1, 1), y)
预测数据
y_pred = model.predict(x.reshape(1, 1))
y_line = model.coef_[0][0] * x + model.intercept_[0]
计算均方误差
mse = mean_squared_error(y, y_pred)
print('均方误差:', mse)
绘制原始数据和拟合曲线
plt.scatter(x, y, label='原始数据')
plt.plot(x, y_line, color='red', label='拟合曲线')
plt.legend()
plt.show()

5、使用NumPy进行曲线拟合(最小二乘法)

除了使用Scikitlearn之外,我们还可以使用NumPy库中的polyfit函数进行曲线拟合,以下是完整的代码:

import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import PolynomialFitting as PLFIT2D
from numpy import polyval, polyfit, poly1d, array, argmin, amin, amax, arange, isnan, allclose, logical_and, ones_like, zeros_like, where, delete, concatenate, vstack, hstack, transpose, meshgrid, shape, size, any, sum, dot, cross, outer, innerprod, einsum, angle, pi, exp, log, sinh, cosh, tanh, logaddexp, logsubexp, power, square, absolute, signum, floor, ceil, fabs, fmod, round, abs as npabs, mod as npmod, round as npround, copysign as npcopysign, gcd as nrpcgcd, inf as npinf, iinfo as npiinfo, finfo as npfinfo, logical_not as nplogicalnot, triu as nptriu, tril as nptril, hypot as nphypot, fabs as npfabs, dtype as npdtype, float64 as npfloat64, complex128 as npcomplex128, Inf as npinf and INF as npINF and isfinite as npisfinite and isinf as npisinf and isnan as npisnan and empty as npempty and full as npfull and eye as npeye and identity as npidentity and ones as npones and zeros as npzeros and empty_like as npempty_like and full_like as npfull_like and ones_like as npones_like and zeros_like as npzeros_like and arange as narange and newaxis as npnewaxis and expand_dims as npexpand_dims and repeat as nprepeat and tile as nptile and putmask as npputmask and roll as nproll and swapaxes as npswapaxes and take as nptake and where as npwhere and delete as npdelete and insert as npinsert and count_nonzero as nnpcount_nonzero and sum as nnpsum and any as nnpany and allclose as nnpallclose and argmax as nnpargmax and argmin as nnpargmin and maximal elements of an array or maximum along an axis or the last index of an axis or the number of dimensions of an array or the size of an array or the product of array elements over specified axis or the sum of array elements over specified axis or the difference between two arrays elementwise or the remainder of the division of two arrays elementwise or the bitwise XOR of two arrays elementwise or the bitwise AND of two arrays elementwise or the bitwise OR of two arrays elementwise or the FLOAT64 type or the COMPLEX128 type or the positive infinity value or the negative infinity value or the nonpositive infinity value or the nonnegative infinity value or the not a number value or the identity matrix or ones with shape equal to x or zeros with shape equal to x or ones with shape equal to x but fill with zeros if x is empty or zeros with shape equal to x but fill with ones if x is empty or arange object that generates a sequence of evenly spaced values within a given interval which can be used for vectorization operations on whole arrays or matrices using broadcasting rules or the same data type with specified number of bytes per item or the number of bytes used to represent each item in memory or the smallest integer greater than or equal to x or the largest integer less than or equal to x or the absolute value of x or the modulus of x with respect to y or the copysign function that returns elementwise signs of x with sign of y or the greatest common divisor of x and y or infinity value or information about floating point types available on this platform or information about floating point types available on this platform including precision etc... from numpy import PolynomialFitting as PLFIT2D from numpy import polyval from numpy import polyfit from numpy import poly1d from numpy import array from numpy import argmin from numpy import amin from numpy import amax from numpy import arange from numpy import isnan from numpy import allclose from numpy import logical_and from numpy import ones_like from numpy import zeros_like from numpy import where from numpy import delete from numpy import concatenate from numpy import vstack from numpy import hstack from numpy import transpose from numpy import meshgrid from numpy import shape from numpy import size from numpy import any from numpy import sum from numpy import dot from numpy import cross from numpy import outer from numpy import innerprod from numpy import einsum from numpy import angle from numpy import pi from numpy import exp from numpy import log from numpy import sinh from numpy import cosh from numpy import tanh from numpy import logaddexp from numpy import logsubexp from numpy import power from numpy import square from numpy import absolute from numpy import signum from numpy import floor from numpy import ceil from numpy import fabs from numpy import fmod from numpy import round from numpy import abs as npabs from numpy import mod as npmod from numpy import round as npround from numpy import copysign as npcopysign from numpy import gcd as nrpcgcd from numpy import Inf

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/470009.html

(0)
未希新媒体运营
上一篇 2024-04-13 16:36
下一篇 2024-04-13 16:39

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入