I have a list of the x-axis and another list of the y-axis values and currently I am finidng the derivative of the gradient as such:
from pylab import polyfit
x = [0,2,3,4]
y = [23,4,34,67]
(m,__) = polyfit(x,y,1)
print m
If I don't want to rely on the pylab/scipy polyfit, how else could I get the deriative?
matplotlib.pylab includes numpy for you, so just use the function numpy.polyfit directly:
import numpy as np
x = [0,2,3,4]
y = [23,4,34,67]
m, __ = np.polyfit(x, y, 1)
print m
Related
I am trying to solve a Weighted Least Squares problem on Python (using numpy) but I am unsure on how to apply the following weight
on
This is what i have done so far
import numpy as np
import matplotlib.pyplot as plt
X = np.random.rand(50) #Generate X values
Y = 2 + 3*X + np.random.rand(50) #Y Values
plt.plot(X,Y,'o')
plt.xlabel('X')
plt.ylabel('Y')
W = ??
X_b = np.c_[np.ones((50,1)), X] #generate [1,x]
beta = np.linalg.inv(X_b.T.dot(W).dot(X_b)).dot(X_b.T).dot(W).dot(Y)
You can use a diagonal matrix for W.
import numpy as np
sigma = # array of [nx1] sigmas
W = np.zeros((len(sigma), len(sigma)) # nxn matrix containing zeros
np.fill_diagonal(W, sigma)
https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html
I have been able to interpolate values successfully from linear values of x to sine-like values of y.
However - I am struggling to interpolate the other way - from nonlinear values of y to linear values of x.
The below is a toy example
import matplotlib.pylab as plt
from scipy import interpolate
#create 100 x values
x = np.linspace(-np.pi, np.pi, 100)
#create 100 values of y where y= sin(x)
y=np.sin(x)
#learn function to map y from x
f = interpolate.interp1d(x, y)
With new values of linear x
xnew = np.array([-1,1])
I get correctly interpolated values of nonlinear y
ynew = f(xnew)
print(ynew)
array([-0.84114583, 0.84114583])
The problem comes when I try and interpolate values of x from y.
I create a new function, the reverse of f:
f2 = interpolate.interp1d(y,x,kind='cubic')
I put in values of y that I successfully interpolated before
ynew=np.array([-0.84114583, 0.84114583])
I am expecting to get the original values of x [-1, 1]
But I get:
array([-1.57328791, 1.57328791])
I have tried putting in other values for the 'kind' parameter with no luck and am not sure if I have got the wrong approach here. Thanks for your help
I guess the problem raises from the fact, that x is not a function of y, since for an arbitrary y value there may be more than one x value found.
Take a look at a truncated range of data.
When x ranges from 0 to np.pi/2, then for every y value there is a unique x value.
In this case the snippet below works as expected.
>>> import numpy as np
>>> from scipy import interpolate
>>> x = np.linspace(0, np.pi / 2, 100)
>>> y = np.sin(x)
>>> f = interpolate.interp1d(x, y)
>>> f([0, 0.1, 0.3, 0.5])
array([0. , 0.09983071, 0.29551713, 0.47941047])
>>> f2 = interpolate.interp1d(y, x)
>>> f2([0, 0.09983071, 0.29551713, 0.47941047])
array([0. , 0.1 , 0.3 , 0.50000001])
Maxim provided the reason for this behavior. This interpolation is a class designed to work for functions. In your case, y=arcsin(x) is only in a limited interval a function. This leads to interesting phenomena in the interpolation routine that interpolates to the nearest y-value which in the case of the arcsin() function is not necessarily the next value in the x-y curve but maybe several periods away. An illustration:
import numpy as np
import matplotlib.pylab as plt
from scipy import interpolate
xmin=-np.pi
xmax=np.pi
fig, axes = plt.subplots(3, 3, figsize=(15, 10))
for i, fac in enumerate([2, 1, 0.5]):
x = np.linspace(xmin * fac, xmax*fac, 100)
y=np.sin(x)
#x->y
f = interpolate.interp1d(x, y)
x_fit = np.linspace(xmin*fac, xmax*fac, 1000)
y_fit = f(x_fit)
axes[i][0].plot(x_fit, y_fit)
axes[i][0].set_ylabel(f"sin period {fac}")
if not i:
axes[i][0].set_title(label="interpolation x->y")
#y->x
f2 = interpolate.interp1d(y, x)
y2_fit = np.linspace(.99 * min(y), .99 * max(y), 1000)
x2_fit = f2(y2_fit)
axes[i][1].plot(x2_fit, y2_fit)
if not i:
axes[i][1].set_title(label="interpolation y->x")
#y->x with cubic interpolation
f3 = interpolate.interp1d(y, x, kind="cubic")
y3_fit = np.linspace(.99 * min(y), .99 * max(y), 1000)
x3_fit = f3(y3_fit)
axes[i][2].plot(x3_fit, y3_fit)
if not i:
axes[i][2].set_title(label="cubic interpolation y->x")
plt.show()
As you can see, the interpolation works along the ordered list of y-values (as you instructed it to), and this works particularly badly with cubic interpolation.
I have 2 numpy arrays with data, say x,y, and I apply plt.step() and get a continues (step) curve of it.
I would like to be able to create this function by my own, meaning I want to have an (zero order hold) step approximation to the value of y for x that does not actually exist in the original x array.
For example, in the following link I want to have the 'new' actual rectangle sine values, and not only plotted:
https://matplotlib.org/gallery/lines_bars_and_markers/step_demo.html#sphx-glr-gallery-lines-bars-and-markers-step-demo-py
You can use scipy's interp1d to create a step function. Default the interpolation is 'linear', but you can change it to 'next', 'previous' or 'nearest' for a step function.
A standard step function is obtained from step_fun = interp1d(x, y, kind='previous') and then calling it as step_fun(new_x).
The following code compares different types of "interpolation":
from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
x = np.random.uniform(0.1, 0.7, 20).cumsum()
y = np.sin(x)
kinds = ['linear', 'previous', 'next', 'nearest', 'cubic']
for i, kind in enumerate(kinds):
function_from_points = interp1d(x, y + i, kind=kind)
x_detailed = np.linspace(x[0], x[-1], 1000)
plt.plot(x_detailed, function_from_points(x_detailed), color='dodgerblue')
plt.scatter(x, y + i, color='crimson')
plt.yticks(range(len(kinds)), kinds)
plt.show()
You can choose tick values and corresponding function values whichever you want. This is an example not equally spaced arguments and their values:
x = np.arange(20) + np.random.random(20)/2
y = np.sin(x / 2)**2 + np.random.random(20)/5
Remark: these two arrays must have equal size. If you want your own custom function, you can use np.vectorise:
x = np.arange(20) + np.random.random(20)/2
func = np.vectorize(lambda x: np.sin(x) + np.random.random()/5)
y = func(x)
I have been trying to get this to work for a while now, but still not finding a way. I am trying to compute the Look ahead estimate density of a piecewise gaussian function. I'm trying to estimate the stationary distribution of a piecewise normally distributed function. is there a way to avoid the error type:
Error-type: the truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
for instance y=np.linspace(-200.0,200.0,100) and x = np,linspace(-200.0,200.0,100). then verify the condition as stated in the code below?
import numpy as np
import sympy as sp
from numpy import exp,sqrt,pi
from sympy import Integral, log, exp, sqrt, pi
import math
import matplotlib.pyplot as plt
import scipy.integrate
from scipy.special import erf
from scipy.stats import norm, gaussian_kde
from quantecon import LAE
from sympy.abc import q
#from sympy import symbols
#var('q')
#q= symbols('q')
## == Define parameters == #
mu=80
sigma=20
b=0.2
Q=80
Q1=Q*(1-b)
Q2=Q*(1+b)
d = (sigma*np.sqrt(2*np.pi))
phi = norm()
n = 500
#Phi(z) = 1/2[1 + erf(z/sqrt(2))].
def p(x, y):
# x, y = np.array(x, dtype=float), np.array(y, dtype=float)
Positive_RG = norm.pdf(x-y+Q1, mu, sigma)
print('Positive_R = ', Positive_RG)
Negative_RG = norm.pdf(x-y+Q2, mu, sigma)
print('Negative_RG = ', Negative_RG)
pdf_0= (1/(2*math.sqrt(2*math.pi)))*(erf((x+Q2-mu)/(sigma*np.sqrt(2)))-erf((x+Q1-mu)/(sigma*np.sqrt(2))))
Zero_RG =norm.pdf
print('Zero_RG',Zero_RG)
print ('y',y)
if y>0.0 and x -y>=-Q1:
#print('printA', Positive_RG)
return Positive_RG
elif y<0.0 and x -y>=-Q2:
#print('printC', Negative_RG)
return Negative_RG
elif y==0.0 and x >=-Q1:
#print('printB', Zero_RG)
return Zero_RG
return 0.0
Z = phi.rvs(n)
X = np.empty(n)
for t in range(n-1):
X[t+1] = X[t] + Z[t]
#X[t+1] = np.abs(X[t]) + Z[t]
psi_est = LAE(p, X)
k_est = gaussian_kde(X)
fig, ax = plt.subplots(figsize=(10,7))
ys = np.linspace(-200.0, 200.0, 200)
ax.plot(ys, psi_est(ys), 'g-', lw=2, alpha=0.6, label='look ahead estimate')
ax.plot(ys, k_est(ys), 'k-', lw=2, alpha=0.6, label='kernel based estimate')
ax.legend(loc='upper left')
plt.show()
See all those ValueError questions in the side bar????
This error is produced when a boolean array is used in a scalar boolean context, such as if or or/and.
Try your y or x in this test, or even simpler one. Experiment in a interactive shell.
if y>0.0 and x -y>=-Q1: ....
if y>0:
(y>0.0) and (x-y>=10)
will all produce this error with your x and y.
Notice also that I edited your question for clarity.
Error starts with quantecon.LAE(p, X), which expects a vectorized function p. Your function isn't vectorized, which is why everything else doesn't work. You copied some vectorized code, but left a lot of things as sympy style functions which is why the numpy folks were confused about what you wanted.
In this case "vectorized" means transforming two 1D arrays with length n into a 2D n x n array. In this case, you don't want to return 0.0, you want to return out a 2d ndArray which has the value 0.0 in locations out[i,j] where a boolean mask based on a function of x[i], y[j] is false.
You can do this by broadcasting:
def sum_function(x,y):
return x[:, None] + y[None, :] # or however you want to add them, broadcasted to 2D
def myFilter(x,y):
x, y = x.squeeze(), y.squeeze()
out=np.zeros((x.size,y.size))
xyDiff = x[:, None] - y[None, :]
out=np.where(np.bitwise_and(y[None, :] => 0.0, xyDiff >= -Q1), sum_function(x, y), out) # unless the sum functions are different
out=np.where(np.bitwise_and(y[None, :] < 0.0, xyDiff >= -Q2), sum_function(x, y), out)
return out
import numpy as np
from scipy.interpolate import PiecewisePolynomial
xi = np.array([1,10])
yi = np.array([10,1])
p = PiecewisePolynomial(xi,yi)
Does not yield a linear interpolation of the two points but
ZeroDivisionError: integer division or modulo by zero
What's wrong there?
Replace your yi with
yi = np.array([[10], [1]])
PiecewisePolynomial requires y array to be an array-like or a list-of-array structure. Each element of y can be a function value for x and its subsequent derivatives. Above change to y creates the correct linear interpolation
p = PiecewisePolynomial(xi,yi)
p.__call__([5.])
>> array([6.])
p.__call__([2.])
>> array([9.])