新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python如何擬合曲線圖
在Python中,我們可以使用多種庫來擬合曲線圖,其中最常用的是Scikitlearn和NumPy,下面將詳細(xì)介紹如何使用這兩個庫進(jìn)行曲線擬合。

1、安裝所需庫
我們需要安裝Scikitlearn和NumPy庫,可以使用以下命令進(jìn)行安裝:
pip install scikitlearn numpy
2、準(zhǔn)備數(shù)據(jù)
在進(jìn)行曲線擬合之前,我們需要準(zhǔn)備一些數(shù)據(jù),這里我們使用一個簡單的例子,假設(shè)我們有一組x和y的數(shù)據(jù),我們想要找到一條曲線來擬合這些數(shù)據(jù)。
import numpy as np import matplotlib.pyplot as plt 生成數(shù)據(jù) x = np.linspace(0, 10, 100) y = np.sin(x) + np.random.normal(0, 0.5, 100) 繪制原始數(shù)據(jù) plt.scatter(x, y, label='原始數(shù)據(jù)') plt.legend() plt.show()
3、使用Scikitlearn進(jìn)行曲線擬合
Scikitlearn提供了多種回歸模型,如線性回歸、多項(xiàng)式回歸、嶺回歸等,下面我們以線性回歸為例,介紹如何使用Scikitlearn進(jìn)行曲線擬合。
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
創(chuàng)建線性回歸模型
model = LinearRegression()
擬合數(shù)據(jù)
model.fit(x.reshape(1, 1), y)
預(yù)測數(shù)據(jù)
y_pred = model.predict(x.reshape(1, 1))
計(jì)算均方誤差
mse = mean_squared_error(y, y_pred)
print('均方誤差:', mse)
4、可視化擬合結(jié)果
我們可以使用matplotlib庫將擬合結(jié)果可視化,以下是完整的代碼:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
生成數(shù)據(jù)
x = np.linspace(0, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.5, 100)
創(chuàng)建線性回歸模型
model = LinearRegression()
擬合數(shù)據(jù)
model.fit(x.reshape(1, 1), y)
預(yù)測數(shù)據(jù)
y_pred = model.predict(x.reshape(1, 1))
y_line = model.coef_[0][0] * x + model.intercept_[0]
計(jì)算均方誤差
mse = mean_squared_error(y, y_pred)
print('均方誤差:', mse)
繪制原始數(shù)據(jù)和擬合曲線
plt.scatter(x, y, label='原始數(shù)據(jù)')
plt.plot(x, y_line, color='red', label='擬合曲線')
plt.legend()
plt.show()
5、使用NumPy進(jìn)行曲線擬合(最小二乘法)
除了使用Scikitlearn之外,我們還可以使用NumPy庫中的polyfit函數(shù)進(jìn)行曲線擬合,以下是完整的代碼:
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
本文名稱:python如何擬合曲線圖
文章源于:http://m.fisionsoft.com.cn/article/dhpichh.html


咨詢
建站咨詢
