x = np.array([x for x in range(1, 31)]) y = np.array([9, 10, 11, 12, 13, 14, 13, 12, 11, 9, 10, 11, 12, 13, 14, 12, 11, 10, 9, 8, 7, 8, 9, 11, 9, 7, 6, 5, 3, 1])对上述数据进行最小二乘法拟合多项式的python代码
时间: 2023-09-07 18:13:41 浏览: 183
可以使用numpy库中的polyfit函数进行最小二乘法拟合多项式。
```python
import numpy as np
# 数据
x = np.array([x for x in range(1, 31)])
y = np.array([9, 10, 11, 12, 13, 14, 13, 12, 11, 9, 10, 11, 12, 13, 14, 12, 11, 10, 9, 8, 7, 8, 9, 11, 9, 7, 6, 5, 3, 1])
# 多项式拟合,返回多项式系数
coeffs = np.polyfit(x, y, deg=3)
# 输出多项式系数
print(coeffs)
```
其中,deg表示拟合多项式的阶数,这里为3表示拟合一个3次多项式,coeffs为拟合多项式的系数。
相关问题
s1x = np.array([sector_x *0, sector_x * 1]) s1y = np.array([sector_y *0, sector_y * 1]) s1z = np.array([sector_z *0, sector_z * 1]) s2x = np.array([sector_x *1, sector_x * 2]) s2y = np.array([sector_y *1, sector_y * 2]) s2z = np.array([sector_z *1, sector_z * 2]) s3x = np.array([sector_x *2, sector_x * 3]) s3y = np.array([sector_y *2, sector_y * 3]) s3z = np.array([sector_z *2, sector_z * 3])
可以将代码精简为如下形式:
```
s1x = np.arange(2) * sector_x
s1y = np.arange(2) * sector_y
s1z = np.arange(2) * sector_z
s2x = np.arange(1, 3) * sector_x
s2y = np.arange(1, 3) * sector_y
s2z = np.arange(1, 3) * sector_z
s3x = np.arange(2, 4) * sector_x
s3y = np.arange(2, 4) * sector_y
s3z = np.arange(2, 4) * sector_z
```
这样可以用 `numpy` 的 `arange` 函数生成等差数列,使代码更加简洁。
修改代码:import numpy as np def dense(a_in, W, b, g): units = W.shape[1] a_out = np.zeros(units) for j in range(units): w = W[:, j] z = np.dot(w, a_in) + b[j] a_out[j] = g(z) return a_out def sequential(x): W1 = np.array([[1],[2]]) b1 = np.array([-1]) W2 = np.array([[-3],[4]]) b2 = np.array([1]) W3 = np.array([[5],[-6]]) b3 = np.array([2]) a1 = dense(x, W1, b1, np.tanh) a2 = dense(a1, W2, b2, np.tanh) a3 = dense(a2, W3, b3, np.tanh) f_x = a3 return f_x a_in = np.array([-2, 4]) print(sequential(a_in))
修改后的代码如下:
```
import numpy as np
def dense(a_in, W, b, g):
units = W.shape[1]
a_out = np.zeros(units)
for j in range(units):
w = W[:, j]
z = np.dot(w, a_in) + b[j]
a_out[j] = g(z)
return a_out
def sequential(x):
W1 = np.array([[1, 2], [3, 4]])
b1 = np.array([-1, -1])
W2 = np.array([[-3, 4], [5, -6]])
b2 = np.array([1, 1])
W3 = np.array([[7, -8], [-9, 10]])
b3 = np.array([2, 2])
a1 = dense(x, W1, b1, np.tanh)
a2 = dense(a1, W2, b2, np.tanh)
a3 = dense(a2, W3, b3, np.tanh)
f_x = a3
return f_x
a_in = np.array([-2, 4])
print(sequential(a_in))
```
主要的修改:
1. 修改了 `W1`、`b1`、`W2`、`b2`、`W3`、`b3` 的维度,使其与输入向量 `x` 和输出向量 `f_x` 的维度匹配。
2. 将 `W1`、`b1`、`W2`、`b2`、`W3`、`b3` 的值修改为与原代码的维度匹配的值。
这样,您应该可以成功运行该代码并得到正确的输出了。
阅读全文