This repository was archived by the owner on Jun 11, 2026. It is now read-only.
PyTorch example for montonic fitting, includes interp1d#746
Open
awf wants to merge 2 commits into
Open
Conversation
Contributor
Author
|
As it's painful to read the ipynb, interp1d is here: def interp1d(x, y, xnew):
"""
PyTorch interp1d, as in scipy.interpolate(x,y,assume_sorted=True)(xnew)
Limited to 1D-1D for now, should not be hard to enhance if needed
github.com/awf
"""
# For each point in x, we want to find index of the knot above it, and hence that below it
# so knots_x[ind-1] <= x < knots_x[ind]
inds = torch.bucketize(xnew, x, right=True)
# Call those points xlo, xhi
xlo = x[inds-1]
xhi = x[inds]
ylo = y[inds-1]
yhi = y[inds]
dx = xhi - xlo
dy = yhi - ylo
# Then t = (xnew - xlo)/dx
# ynew = ylo + t * dy
t = (xnew - xlo) / dx
return ylo + t * dy
def test_interp1d():
# scipy example from https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
import scipy.interpolate
import numpy as np
x = np.arange(0, 10)
y = np.exp(-x/3.0)
f = scipy.interpolate.interp1d(x, y)
xnew = np.arange(0, 9, 0.1)
ynew = f(xnew) # use interpolation function returned by `interp1d`
# Now do it with torch
tx = torch.arange(0, 10)
ty = torch.exp(-tx/3.0)
txnew = torch.arange(0, 9, 0.1)
tynew = interp1d(tx,ty,txnew)
plt.figure()
plt.plot(x, y, 'ro', xnew, ynew, 'r-',
tx, ty, 'kx', txnew, tynew, 'k:')
plt.show()
test_interp1d() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A notebook showing fitting of monotonic function using the relu(w[i] - w[i+1]) penalty
Starting here:

Optimize to here:
