当前试图使用scipy的interpaly实现来创建一个均匀的立方体B型单键(夹紧(。当使用interpaly.splev((时,i传递的目标(x(值已更改,并且该函数返回我的x值接近但与目标值不相同(以及错误的x值的正确y值(。有人对我如何解决这个问题有任何建议吗?下面提供的代码重新创建问题。非常感谢您:(
import numpy as np
import random as rd
from scipy import interpolate
import matplotlib.pyplot as plt
# The number of knots to form spline.
knots = 11
# Creating the x and y values for the knots.
x = np.linspace(0, 1, knots, endpoint=True)
y = np.array([rd.random() for i in range(knots)])
# Knot Vector.
t = np.linspace(0, 1, len(x) - 2, endpoint=True)
t = np.append([0, 0, 0], t)
t = np.append(t, [1, 1, 1])
# Cubic Spline definition.
spline = [t, [x, y], 3]
# =====================================================================
# X value I want to predict the y value off.
target = rd.random()
# Using spline evaluate to get the value of the "target".
prediction = interpolate.splev(target, spline)
print("X Value given to .splev:", target)
print("What .splev sees: x =", prediction[0], ", y =", prediction[1])
# =====================================================================
# Plotting the control points.
plt.plot(x, y, 'k--', label='Control Polygon', marker='o', markerfacecolor='red')
# Output used for display purposes only.
out = interpolate.splev(np.linspace(0, 1, 1000, endpoint=True), spline)
# Plotting the b-spline line.
plt.plot(out[0], out[1], 'b', linewidth=2.0, label='B-spline curve')
plt.grid(True)
plt.show()
更新的代码:
import matplotlib.pyplot as plt
from scipy.interpolate import splev, splrep
import numpy as np
import random as rd
knots = 11
# X knots equidistant apart and Y random.
x = np.linspace(0, 1, knots, endpoint=True)
y = np.array([rd.random() for i in range(knots)])
# Creating the spline using slrep.
spline = splrep(x, y, s=0)
x2 = np.linspace(0, 1, 200)
y2 = splev(x2, spline)
# Plotting the a random point with target (x) and the predicted (y).
target = rd.random()
prediction = splev(target, spline)
plt.plot(target, prediction, 'o')
# Plotting the spline.
plt.plot(x, y, 'o', x2, y2)
plt.grid(True)
plt.show()
splev接受结的元组和系数。要适合数据,请使用tck= splrep(x, y, s=0); splev(xnew, tck)
或make_interp_spline
。
要使用给定系数创建一个蓬松的对象,请使用BSpline(t, c, k)