Please can you help me ? I have non linear data that fit in an asymmetrical sigmoid function. So I've generated a sigmoid function. And I've used that in the curve_fit function to generate a beta1 and beta2. But the sigmoid function that I have accepts only one input variable. Is there a sigmoid function that accepts multiple input variables ? Here is my code for the train_test_split, the sigmoid and the curve_fit functions :
X_train, X_test, y_train, y_test = train_test_split(df.drop('Montant TLPE', axis=1).values, df['Montant TLPE'].values, random_state=0, test_size=0.2)
def sigmoid(x, Beta_1, Beta_2):
y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2)))
return y
from scipy.optimize import curve_fit
popt, pcov = curve_fit(sigmoid, np.array(X_train), np.array(y_train))
print(" beta_1 = %f, beta_2 = %f" % (popt[0], popt[1]))
Thanks a lot for your help.
Here is the scatter plot of my data
Related
I have a question about plotting x(t), the solution to the following differential equation knowing that dx/dt equals the expression below. The value of x is 0 at t = 0.
syms x
dxdt = -(1.0*(6.84e+45*x^2 + 5.24e+32*x - 2.49e+42))/(2.47e+39*x + 7.12e+37)
I want to plot the solution of this first-order nonlinear differential equation. The analytical solution involves complex numbers so that's not relevant because this equation models a real-life process, but Matlab can solve the equation using numerical methods and plot it. Can someone please suggest how to do this?
in matlab try this
tspan = [0 10];
x0 = 0;
[t,x] = ode45(#(t,x) -(1.0*(6.84e+45*x^2 + 5.24e+32*x - 2.49e+42))/(2.47e+39*x + 7.12e+37), tspan, x0);
plot(t,x,'b')
i try it and i got this
hope that help you.
I have written an example for how to use Python with SymPy and matplotlib. SymPy can be used to calculate both definite and indefinite integrals. By calculating the indefinite integral and adding a constant to set it to evaluate to 0 at t = 0. Now you have the integral, so just a matter of plotting. I would define an array from a starting point to an endpoint with 1000 points between (could likely be less). You can then calculate the value of the integral with the constant at each time point, which can then be plotted with matplotlib. There are plenty of other questions on how to customize plots with matplotlib.
This displays a basic plot of the indefinite integral of the function dxdt with assumption of x(t) = 0. Variation of the tuple when running Plotting() will set what range of x values to plot. This is set to plot 1000 data points between the minimum and maximum values set when calling the function.
For more information on customizing the plot, I recommend matplotlib documentation. Documentation on the integral can be found in SymPy documentation.
import pandas as pd
from sympy import *
from sympy.abc import x
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def Plotting(xValues, dxdt):
# Calculate integral
xt = integrate(dxdt,x)
# Convert to function
f = lambdify(x, xt)
C = -f(0)
# Define x values, last number in linspace corresponding to number of points to plot
xValues = np.linspace(xValues[0],xValues[1],500)
yValues = [f(x)+C for x in xValues]
# Initialize figure
fig = plt.figure(figsize = (4,3))
ax = fig.add_axes([0, 0, 1, 1])
# Plot Data
ax.plot(xValues, yValues)
plt.show()
plt.close("all")
# Define Function
dxdt = -(1.0*(6.84e45*x**2 + 5.24e32*x - 2.49e42))/(2.47e39*x + 7.12e37)
# Run Plotting function, with left and right most points defined as tuple, and function as second argument
Plotting((-0.025, 0.05),dxdt)
I have a simple linear multiple regression in Python that looks like this:
X_train,X_test,y_train,y_test=train_test_split(x_cols,df['Volume'],test_size=0.15)
regr = LinearRegression()
regr.fit(X_train, y_train)
y_pred = regr.predict(X_test)
How do I plot the residuals of this model?
At first I tried this:
sns.residplot(y_pred, y_test)
But I'm not sure if this is actually displaying the residuals of the linear regression. Do I have the right arguments passed to residplot?
Nope, you need to pass your x and y as arguments and residplot will run the regression and plot the residuals.
You can read more about residplot here:
df = pd.DataFrame({
'X':np.random.randn(60),
'Y':np.random.randn(60),
})
sns.residplot('X','Y',data=df)
I have an ODE:
x' = -x + f(x)
Looks simple enough, but x is 100 dimensional i.e.
x = [x1, ... , x100]
Furthermore,
fi(x) = ln(xi)/(ln(x1)+...+ln(x100))
where i is between 1 and 100 and f(x) = [f1(x), ... , f100(x)]
On MATLAB's website, it says I should first create a function as:
But how can I do this? I have 100 variables, and all my variables are coupled through that highly nonlinear function.
Any help is greatly appreciated!
The function can leverage the vectorization capabilities of MATLAB since, from the ode45 documentation, the "function dydt = odefun(t,y), for a scalar t and a column vector y, must return a column vector dydt". So your odefun can be expressed simply as
function dxdt = odefun(~,x)
logX = log(x);
dxdt = -x + logX/sum(logX);
end
and let ode45, or another appropriate integrator, handle the rest.
I have a data-set which is loaded into matlab. I need to do exponential fitting for the plotted curve without using the curve fitting tool cftool.
I want to do this manually through executing a code/function that will output the values of a and b corresponding to the equation:
y = a*exp(b*x)
Then be using those values, I will do error optimization and create the best fit for the data I have.
Any help please?
Thanks in advance.
Try this...
f = fit(x,y,'exp1');
I think the typical objective in this type of assignment is to recognize that by taking the log of both sides, various methods of polynomial fit approaches can be used.
ln(y) = ln(a) + ln( exp(x).^b )
ln(y) = ln(a) + b * ln( exp(x) )
There can be difficulties with this approach when errors such as noise are involved due to the behavior of ln as it approaches zero.
In this exercise I have a set of data that present an exponential curve and I want to fit them exponentially and get the values of a and b. I used the following code and it worked with the data I have.
"trail.m" file:
%defining the data used
load trialforfitting.txt;
xdata= trialforfitting(:,1);
ydata= trialforfitting(:,2);
%calling the "fitcurvedemo" function
[estimates, model] = fitcurvedemo(xdata,ydata)
disp(sse);
plot(xdata, ydata, 'o'); %Data curve
hold on
[sse, FittedCurve] = model(estimates);
plot(xdata, FittedCurve, 'r')%Fitted curve
xlabel('Voltage (V)')
ylabel('Current (A)')
title('Exponential Fitting to IV curves');
legend('data', ['Fitting'])
hold off
"fitcurvedemo.m" file:
function [estimates, model] = fitcurvedemo(xdata, ydata)
%Call fminsearch with a random starting point.
start_point = rand(1, 2);
model = #expfun;
estimates = fminsearch(model, start_point);
%"expfun" accepts curve parameters as inputs, and outputs
%the sum of squares error [sse] expfun is a function handle;
%a value that contains a matlab object methods and the constructor
%"FMINSEARCH" only needs sse
%estimate returns the value of A and lambda
%model computes the exponential function
function [sse, FittedCurve] = expfun(params)
A = params(1);
lambda = params(2);
%exponential function model to fit
FittedCurve = A .* exp(lambda * xdata);
ErrorVector = FittedCurve - ydata;
%output of the expfun function [sum of squares of error]
sse = sum(ErrorVector .^ 2);
end
end
I have a new set of data that doesn't work with this code and give the appropriate exponential fit for the data curve plotted.
I'm trying to draw random numbers from a multivariate t-student distribution (with a specified mean, variance and df) in Matlab.
Looking into the matlab documentation, I've found the "mvtrnd" function (http://www.mathworks.it/it/help/stats/mvtrnd.html), but unfortunately, it returns values centered in 0.
Could you suggest me any other function or approach to solve my problem?
EDIT:
I think I have solved the problem writing the function below. I have found in wikipedia that if X is distributed as a multivariate t-student (mu, $$\Sigma$$, df) and Y as a multivariate normal (0, $$\Sigma$$), than $$X = \mu + Y * \sqrt{\frac{df}{\chi^2_{df}}}$$.
function [ output ] = st_rndmvt( mu, sigma, df, cases )
if nargin < 4
cases = 1;
end
mu = mu(:)';
output = zeros(cases, length(mu));
for i=1:cases
output(i, :) = mu + mvnrnd(zeros(length(sigma), 1), sigma) * sqrt(df/chi2rnd(df));
end
end