python未知函数梯度 python计算未知数( 三 )


N = int(sys.argv[1])
weights = np.ones(N) / N
print "Weights", weights
在N = 5时,输出结果如下:
Weights [ 0.2 0.2 0.2 0.2 0.2] #权重相等
(2) 使用这些权重值,调用convolve函数:
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
sma = np.convolve(weights, c)[N-1:-N+1] #卷积是分析数学中一种重要的运算 , 定义为一个函数与经过翻转和平移的另一个函数的乘积的积分 。
t = np.arange(N - 1, len(c)) #作图
plot(t, c[N-1:], lw=1.0)
plot(t, sma, lw=2.0)
show()
3.22 计算指数移动平均线
指数移动平均线(exponential moving average) 。指数移动平均线使用的权重是指数衰减的 。对历史上的数据点赋予的权重以指数速度减小,但永远不会到达0 。
x = np.arange(5)
print "Exp", np.exp(x)
#output
Exp [ 1. 2.71828183 7.3890561 20.08553692 54.59815003]
Linspace 返回一个元素值在指定的范围内均匀分布的数组 。
print "Linspace", np.linspace(-1, 0, 5) #起始值、终止值、可选的元素个数
#output
Linspace [-1. -0.75 -0.5 -0.25 0. ]
(1)权重计算
N = int(sys.argv[1])
weights = np.exp(np.linspace(-1. , 0. , N))
(2)权重归一化处理
weights /= weights.sum()
print "Weights", weights
#output
Weights [ 0.11405072 0.14644403 0.18803785 0.24144538 0.31002201]
(3)计算及作图
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
ema = np.convolve(weights, c)[N-1:-N+1]
t = np.arange(N - 1, len(c))
plot(t, c[N-1:], lw=1.0)
plot(t, ema, lw=2.0)
show()
3.26 用线性模型预测价格
(x, residuals, rank, s) = np.linalg.lstsq(A, b) #系数向量x、一个残差数组、A的秩以及A的奇异值
print x, residuals, rank, s
#计算下一个预测值
print np.dot(b, x)
3.28 绘制趋势线
x = np.arange(6)
x = x.reshape((2, 3))
x
array([[0, 1, 2], [3, 4, 5]])
np.ones_like(x) #用1填充数组
array([[1, 1, 1], [1, 1, 1]])
类似函数
zeros_like
empty_like
zeros
ones
empty
3.30 数组的修剪和压缩
a = np.arange(5)
print "a =", a
print "Clipped", a.clip(1, 2) #将所有比给定最大值还大的元素全部设为给定的最大值,而所有比给定最小值还小的元素全部设为给定的最小值
#output
a = [0 1 2 3 4]
Clipped [1 1 2 2 2]
a = np.arange(4)
print a
print "Compressed", a.compress(a2) #返回一个根据给定条件筛选后的数组
#output
[0 1 2 3]
Compressed [3]
b = np.arange(1, 9)
print "b =", b
print "Factorial", b.prod() #输出数组元素阶乘结果
#output
b = [1 2 3 4 5 6 7 8]
Factorial 40320
print "Factorials", b.cumprod()
#output
如何使用python计算常微分方程?常用形式
odeint(func, y0, t,args,Dfun)
一般这种形式就够用了 。
下面是官方的例子,求解的是
D(D(y1))-t*y1=0
为了方便,采取D=d/dt 。如果我们令初值
y1(0) = 1.0/3**(2.0/3.0)/gamma(2.0/3.0)
D(y1)(0) = -1.0/3**(1.0/3.0)/gamma(1.0/3.0)
这个微分方程的解y1=airy(t) 。
令D(y1)=y0,就有这个常微分方程组 。
D(y0)=t*y1
D(y1)=y0
Python求解该微分方程 。
from scipy.integrate import odeint
from scipy.special import gamma, airy
y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0)
y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0)
y0 = [y0_0, y1_0]
def func(y, t):
...return [t*y[1],y[0]]
def gradient(y,t):
...return [[0,t],[1,0]]
x = arange(0,4.0, 0.01)
t = x
ychk = airy(x)[0]
y = odeint(func, y0, t)
y2 = odeint(func, y0, t, Dfun=gradient)