Python 优化线性函数逼近
在阅读了函数描述之后,我研究了函数近似方法,发现(可能是错误的)它们只近似非线性函数 例如,如果我在Python 优化线性函数逼近,python,numpy,scipy,approximation,Python,Numpy,Scipy,Approximation,在阅读了函数描述之后,我研究了函数近似方法,发现(可能是错误的)它们只近似非线性函数 例如,如果我在zip()函数之后为x和y [(1,1),(4,2),(6,4),(8,6),(10,11)] 正如你们所看到的,非线性函数逼近得更好,但我需要线性函数 我承认在函数的文档中可能遗漏了一些内容,所以,如果可以用“阅读文档”的方式回答这个问题,我深表歉意 你试过最小二乘法合适的方法吗? 另外,如果我没记错的话,numpy的polyfit有一个选项来确定您所需的自由度,在您的情况下,它将是一个自由度
zip()
函数之后为x
和y
[(1,1),(4,2),(6,4),(8,6),(10,11)]
正如你们所看到的,非线性函数逼近得更好,但我需要线性函数
我承认在函数的文档中可能遗漏了一些内容,所以,如果可以用“阅读文档”的方式回答这个问题,我深表歉意 你试过最小二乘法合适的方法吗? 另外,如果我没记错的话,numpy的polyfit有一个选项来确定您所需的自由度,在您的情况下,它将是一个自由度
importing polyfit from numpy... etc.
coefficients = polyfit( xlist, ylist, 1 ) #where 1 is the degree of freedom
p = poly1d( coefficients )
x = linspace( 0, 5, 100 ) #generates 100 points between 0 and 5 to plot 'curve'
plot( x, p(x), label='Best Fit Line' )
希望对你有所帮助你试过最小二乘法吗? 另外,如果我没记错的话,numpy的polyfit有一个选项来确定您所需的自由度,在您的情况下,它将是一个自由度
importing polyfit from numpy... etc.
coefficients = polyfit( xlist, ylist, 1 ) #where 1 is the degree of freedom
p = poly1d( coefficients )
x = linspace( 0, 5, 100 ) #generates 100 points between 0 and 5 to plot 'curve'
plot( x, p(x), label='Best Fit Line' )
希望有帮助除了@user2589273建议的
np.polyfit
和scipy.stats.linregresse
之外,进行线性回归的低级方法是使用np.linalg.lstsq
求解系数矩阵。虽然这种方法比使用一个预先打包的函数来进行线性回归要复杂一些,但了解它在基本层面上的工作原理是非常有用的,特别是当您开始处理多元数据时
例如:
import numpy as np
# a simple linear relationship: y = mx + c with m=0.5 and c=2
x = np.arange(50)
y = x * 0.5 + 2
y += np.random.randn(50) * 5 # add some noise
# we can rewrite the line equation as y = Ap, where A=[[x, 1]] and p=[[m], [c]]
A = np.c_[x, np.ones(50)]
# solving for p gives us the slope and intercept
p, residuals, rank, svals = np.linalg.lstsq(A, y)
绘制拟合曲线:
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(x, y, 'ob', label='data')
ax.plot(x, A.dot(p), '-k', lw=2, label='linear fit')
ax.legend()
除了@user2589273建议的
np.polyfit
和scipy.stats.linregresse
之外,进行线性回归的低级方法是使用np.linalg.lstsq
求解系数矩阵。虽然这种方法比使用一个预先打包的函数来进行线性回归要复杂一些,但了解它在基本层面上的工作原理是非常有用的,特别是当您开始处理多元数据时
例如:
import numpy as np
# a simple linear relationship: y = mx + c with m=0.5 and c=2
x = np.arange(50)
y = x * 0.5 + 2
y += np.random.randn(50) * 5 # add some noise
# we can rewrite the line equation as y = Ap, where A=[[x, 1]] and p=[[m], [c]]
A = np.c_[x, np.ones(50)]
# solving for p gives us the slope and intercept
p, residuals, rank, svals = np.linalg.lstsq(A, y)
绘制拟合曲线:
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.plot(x, y, 'ob', label='data')
ax.plot(x, A.dot(p), '-k', lw=2, label='linear fit')
ax.legend()
我会看一看,然后带着结果回来。我会看一看,然后带着结果回来。谢谢你的回复。没有从矩阵
a
中确定斜率a
(对于ax+b
形式)(如果我从文档中得到正确的话)。或者numpy会帮我处理这个问题?在这种情况下,p
将是一个大小(2,)
数组,包含[梯度,截距]
谢谢您的回复。没有从矩阵a
中确定斜率a
(对于ax+b
形式)(如果我从文档中得到正确的话)。或者numpy会为我处理这个问题?在这种情况下,p
将是一个大小(2,)
数组,包含[梯度,截距]