```python
import scipy.linalg as sla
import numpy as np
import sympy as sy
sy.init_printing()
from matplotlib import pyplot as plt
%matplotlib inline
```

# curve fitting


```python
m=400
x=np.linspace(-2,2,m)
a,b,c=0.5,1,-2
y_true=a+b*x+c*x**2
```


```python
#note
# rand(m,1) <- m行1列の0から1の値をとる一様乱数
#randn(m,1)<- m行1列の標準正規分布の値を成分にもつ
```


```python
#generate random X in [-2,2]
X=2-4*np.random.rand(m,1)
#generate Y -value and add randn noise
Y=a+b*X+c*X*X+2*np.random.randn(m,1)
```


```python
A=np.hstack([X**0,X**1,X**2])
```


```python
sol,r,rank,s=sla.lstsq(A,Y)
```


```python
sol
```




    array([[ 0.44966843],
           [ 1.01688223],
           [-1.99152264]])




```python
y_fit=sol[0]+sol[1]*x+sol[2]*x**2
fig,ax=plt.subplots()
ax.plot(X,Y,'x',label='data pt')
ax.plot(x,y_true,'k--',label='true')
ax.plot(x,y_fit,'r',label='fit')
ax.set_xlabel(r'$x$',fontsize=16)
ax.set_ylabel(r'$y$',fontsize=16)
ax.legend(loc=0)
```

# ムーアペンローズの擬似逆行列


```python
sol=sla.pinv(A)@ Y
sol
```




    array([[ 0.44966843],
           [ 1.01688223],
           [-1.99152264]])



# もうちょっと賢いcurve-fitting


```python
from scipy.optimize import curve_fit
```


```python
def func(x,a,b,c):
    return a+b*x+c*x**2
```


```python
popt,pcov=curve_fit(func,X.ravel(),Y.ravel())
popt
```




    array([ 0.44966843,  1.01688222, -1.99152264])




```python
y_fit=popt[0]+popt[1]*x+popt[2]*x**2
fig,ax=plt.subplots()
ax.plot(X,Y,'x',label='data pt')
ax.plot(x,y_true,'k--',label='true')
ax.plot(x,y_fit,'r',label='fit')
ax.set_xlabel(r'$x$',fontsize=16)
ax.set_ylabel(r'$y$',fontsize=16)
ax.legend(loc=0)
```


```python

```


```python

```


```python

```


```python

```

719e546a80feb5e8cab4a1bb4d51c957f305ad0e
ipynb
Jupyter Notebook
sympyExercise/Curve-fitting.ipynb
terasakisatoshi/pythonCodes
baee095ecee96f6b5ec6431267cdc6c40512a542
MIT
sympyExercise/Curve-fitting.ipynb
terasakisatoshi/pythonCodes
baee095ecee96f6b5ec6431267cdc6c40512a542
MIT
sympyExercise/Curve-fitting.ipynb
terasakisatoshi/pythonCodes
baee095ecee96f6b5ec6431267cdc6c40512a542
MIT
Qwen/Qwen-72B
1. YES
2. YES