问题
Currently trying to use scipy's implementation of interpolate to create a uniform cubic B-spline (clamped). When using interpolate.splev() the target (x) value I pass in is changed and the function returns me the x value of a point near but not the same as the target value (and the correct y value for the wrong x value). Anybody got any advice on how I can resolve this problem? Code provided below to recreate problem. Thank you very much in advance :)
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()
Updated Code:
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()
回答1:
splev accepts a tuple of knots and coefficients. To fit the data, use tck= splrep(x, y, s=0); splev(xnew, tck)
, or make_interp_spline
.
To create a splne object with given coefficients, use BSpline(t, c, k)
来源:https://stackoverflow.com/questions/57318761/scipy-interpolate-problems-with-inputing-values