一维和二维的局部线性和局部二次回归 生成python代码
时间: 2024-05-16 13:15:50 浏览: 45
一维局部线性回归的Python代码:
```python
import numpy as np
from scipy import linalg
def locallinear(x, y, tau):
n = len(x)
xmat = np.ones((n,2))
xmat[:,1] = x
ypred = np.zeros(n)
for i in range(n):
weights = np.exp(-(x-x[i])**2/(2*tau**2))
wmat = np.diag(weights)
beta = linalg.inv(xmat.T @ wmat @ xmat) @ xmat.T @ wmat @ y
ypred[i] = beta[0] + beta[1]*x[i]
return ypred
```
二维局部线性回归的Python代码:
```python
import numpy as np
from scipy import linalg
def locallinear2d(x, y, z, taux, tauy):
n = len(x)
xmat = np.ones((n,3))
xmat[:,1] = x
xmat[:,2] = y
zpred = np.zeros(n)
for i in range(n):
weights = np.exp(-(x-x[i])**2/(2*taux**2)-(y-y[i])**2/(2*tauy**2))
wmat = np.diag(weights)
beta = linalg.inv(xmat.T @ wmat @ xmat) @ xmat.T @ wmat @ z
zpred[i] = beta[0] + beta[1]*x[i] + beta[2]*y[i]
return zpred
```
局部二次回归的Python代码:
```python
import numpy as np
from scipy import linalg
def localquadratic(x, y, tau):
n = len(x)
xmat = np.ones((n,3))
xmat[:,1] = x
xmat[:,2] = x**2
ypred = np.zeros(n)
for i in range(n):
weights = np.exp(-(x-x[i])**2/(2*tau**2))
wmat = np.diag(weights)
beta = linalg.inv(xmat.T @ wmat @ xmat) @ xmat.T @ wmat @ y
ypred[i] = beta[0] + beta[1]*x[i] + beta[2]*x[i]**2
return ypred
```
阅读全文