Mathematica - plotting an array with values and exponential function - arrays
I have a question about mathematica. I have an array with values called tempDep:
{10.7072,11.5416,12.2065,12.774,13.2768,13.7328,14.1526,14.5436,14.9107,15.2577,15.5874,15.9022,16.2037,16.4934,16.7727,17.0425,17.3036,17.5569,17.803,18.0424,18.2756,18.503,18.725,18.9419,19.154,19.3615,19.5647,19.7637,19.9588,20.1501,20.3378,20.5219,20.7025,20.8799,21.0541,21.2252,21.3933,21.5584,21.7207,21.8801,22.0368,22.1908,22.3423,22.4911,22.6374,22.7813,22.9228,23.0619,23.1987,23.3332,23.4655,23.5955,23.7235,23.8493,23.973,24.0947,24.2143,24.332,24.4478,24.5616,24.6736,24.7837,24.892,24.9986,25.1034,25.2064,25.3078,25.4075,25.5055,25.602,25.6968,25.7901,25.8819,25.9722,26.061,26.1483,26.2342,26.3186,26.4017,26.4835,26.5638,26.6429,26.7207,26.7972,26.8724,26.9464,27.0192,27.0908,27.1612,27.2304,27.2986,27.3656,27.4315,27.4963,27.56,27.6227,27.6844,27.7451,27.8048,27.8635,27.9212,27.978,28.0338,28.0887,28.1428,28.1959,28.2482,28.2996,28.3502,28.3999,28.4488,28.497,28.5443,28.5908,28.6366,28.6817,28.726,28.7695,28.8124,28.8545,28.896,28.9368,28.9769,29.0163,29.0551,29.0933,29.1308,29.1678,29.2041,29.2398,29.2749,29.3095,29.3435,29.3769,29.4098,29.4421,29.474,29.5053,29.536,29.5663,29.5961,29.6254,29.6542,29.6825,29.7104,29.7378,29.7647,29.7913,29.8173,29.843,29.8682,29.893,29.9175,29.9415,29.9651,29.9883,30.0112,30.0336,30.0557,30.0775,30.0989,30.1199,30.1406,30.1609,30.1809,30.2006,30.22,30.239,30.2578,30.2762,30.2943,30.3121,30.3297,30.3469,30.3639,30.3806,30.397,30.4131,30.429,30.4446,30.4599,30.4751,30.4899,30.5045,30.5189,30.533,30.5469,30.5606,30.5741,30.5873,30.6003,30.6131,30.6257,30.6381,30.6503,30.6623,30.674,30.6856}
and I am plotting it using
ListPlot[tempDep]
What I want to do is to display this plot together with an exponential (that should look pretty much the same as this listPlot) in one graph. Can u help me out with this plz?
Perhaps something like this?
data = Table[Sin[x], {x, 0, 2 Pi, 0.3}];
Show[
ListPlot[data, PlotStyle -> PointSize[0.02]],
ListLinePlot[data,
InterpolationOrder -> 2,
PlotStyle -> Directive[Thick, Orange]]
]
You can use
f = Interpolate[tempDep]
and then plot the graph of interpolating function with
Plot[f,{x,1,198}]
It seems to me that your data obey something else, but if you want an exponential fit:
model = a + b Exp[c + d x];
tempDep1 = Partition[Riffle[Range#Length#tempDep, tempDep], 2];
fit = FindFit[tempDep1, model, {a, b, c, d}, x, Method -> NMinimize];
modelf = Function[{x}, Evaluate[model /. fit]]
Plot[modelf[t], {t, 0, Length#tempDep}, Epilog -> Point#tempDep1]
Related
When to use transposition for plotting contour in Julia
So I tried to plot a contour in Julia by interpolating a 2D function, using the following code: using Interpolations using Plots gr() xs = 1:0.5:5 ys = 1:0.5:8 # The function to be plotted f(x, y) = (3x + y ^ 2) g = Float64[f(x,y) for x in xs, y in ys] # Interpolate the function g_int = interpolate(g, BSpline(Quadratic(Line(OnCell())))) # Scale the interpolated function to the correct grid gs_int = scale(g_int, xs, ys) xc = 1:0.1:5 yc = 1:0.1:5 # Compare the real value and the interpolated value of the function at an arbitrary point println("gs_int(3.2, 3.2) = ", gs_int(3.2, 3.2)) println("f(3.2, 3.2) = ", f(3.2, 3.2)) # Contour of the interpolated plot p1 = contour(xs, ys, gs_int(xs, ys), fill=true) # Real contour of the function p2 = contour(xc, yc, f, fill=true) plot(p1, p2) And this obviously didn't give the correct contour, although the interpolation was seemingly correct: The problem was fixed by transposing gs_int(xs, ys): p1 = contour(xs, ys, gs_int(xs, ys)', fill=true) Then I randomly generated some points in 2D space, and repeated the same procedures: using DelimitedFiles using Interpolations using Plots gr() data = readdlm("./random_points.txt", Float64) # Create a dictionary to test different orders of interpolations. inter = Dict("constant" => BSpline(Constant()), "linear" => BSpline(Linear()), "quadratic" => BSpline(Quadratic(Line(OnCell()))), "cubic" => BSpline(Cubic(Line(OnCell()))) ) x = range(-10, length=64, stop=10) y = range(-10, length=64, stop=10) v_unscaled = interpolate(data, inter["cubic"]) v = scale(v_unscaled, x, y) # The contour of the data points p0 = contour(x, y, data, fill=true) display(p0) # The contour of the interpolated function p_int = contour(x, y, v(x,y)', fill=true) display(p_int) However the two contour plots don't look the same. As I removed the apostrophe after v(x,y), this worked: p_int = contour(x, y, v(x,y), fill=true) Now I don't get it. When should I apply transposition, and when shouldn't I do so?
That's because in your first example you plot a function, in the second example you plot two arrays. The two arrays don't need to be transposed as they are oriented the same way. But in the first example, the way you generate the array is transposed relative to the way Plots generates an array from the 2-d function you're passing. When you plot a function, Plots will calculate the outcome as g = Float64[f(x,y) for y in ys, x in xs] not the other way around, like you did in your code. For a good discussion of transposes in plotting, again refer to https://github.com/JuliaPlots/Makie.jl/issues/205
What would be an idiomatic F# way to scale a list of (n-tuples or list) with another list, also arrays?
Given: let weights = [0.5;0.4;0.3] let X = [[2;3;4];[7;3;2];[5;3;6]] what I want is: wX = [(0.5)*[2;3;4];(0.4)*[7;3;2];(0.3)*[5;3;6]] would like to know an elegant way to do this with lists as well as with arrays. Additional optimization information is welcome
You write about a list of lists, but your code shows a list of tuples. Taking the liberty to adjust for that, a solution would be let weights = [0.5;0.4;0.3] let X = [[2;3;4];[7;3;2];[5;3;6]] X |> List.map2 (fun w x -> x |> List.map (fun xi -> (float xi) * w ) ) weights Depending on how comfortable you are with the syntax, you may prefer a oneliner like List.map2 (fun w x -> List.map (float >> (*) w) x) weights X The same library functions exist for sequences (Seq.map2, Seq.map) and arrays (in the Array module).
This is much more than an answer to the specific question but after a chat in the comments and learning that the question was specifically a part of a neural network in F# I am posting this which covers the question and implements the feedforward part of a neural network. It makes use of MathNet Numerics This code is an F# translation of part of the Python code from Neural Networks and Deep Learning. Python def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # feedforward activation = x activations = [x] # list to store all the activations, layer by layer zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = sigmoid(z) activations.append(activation) F# module NeuralNetwork1 = //# Third-party libraries open MathNet.Numerics.Distributions // Normal.Sample open MathNet.Numerics.LinearAlgebra // Matrix type Network(sizes : int array) = let mutable (_biases : Matrix<double> list) = [] let mutable (_weights : Matrix<double> list) = [] member __.Biases with get() = _biases and set value = _biases <- value member __.Weights with get() = _weights and set value = _weights <- value member __.Backprop (x : Matrix<double>) (y : Matrix<double>) = // Note: There is a separate member for feedforward. This one is only used within Backprop // Note: In the text layers are numbered from 1 to n with 1 being the input and n being the output // In the code layers are numbered from 0 to n-1 with 0 being the input and n-1 being the output // Layers // 1 2 3 Text // 0 1 2 Code // 784 -> 30 -> 10 let feedforward () : (Matrix<double> list * Matrix<double> list) = let (bw : (Matrix<double> * Matrix<double>) list) = List.zip __.Biases __.Weights let rec feedfowardInner layer activation zs activations = match layer with | x when x < (__.NumLayers - 1) -> let (bias, weight) = bw.[layer] let z = weight * activation + bias let activation = __.Sigmoid z feedfowardInner (layer + 1) activation (z :: zs) (activation :: activations) | _ -> // Normally with recursive functions that build list for returning // the final list(s) would be reversed before returning. // However since the returned list will be accessed in reverse order // for the backpropagation step, we leave them in the reverse order. (zs, activations) feedfowardInner 0 x [] [x] In weight * activation * is an overloaded operator operating on Matrix<double> Related back to your example data and using MathNet Numerics Arithmetics let weights = [0.5;0.4;0.3] let X = [[2;3;4];[7;3;2];[5;3;6]] first the values for X need to be converted to float let x1 = [[2.0;3.0;4.0];[7.0;3.0;2.0];[5.0;3;0;6;0]] Now notice that x1 is a matrix and weights is a vector so we can just multiply let wx1 = weights * x1 Since the way I validated the code was a bit more than most I will explain it so that you don't have doubts to its validity. When working with Neural Networks and in particular mini-batches, the starting numbers for the weights and biases are random and the generation of the mini-batches is also done randomly. I know the original Python code was valid and I was able to run it successfully and get the same results as indicated in the book, meaning that the initial successes were within a couple of percent of the book and the graphs of the success were the same. I did this for several runs and several configurations of the neural network as discussed in the book. Then I ran the F# code and achieved the same graphs. I also copied the starting random number sets from the Python code into the F# code so that while the data generated was random, both the Python and F# code used the same starting numbers, of which there are thousands. I then single stepped both the Python and F# code to verify that each individual function was returning a comparable float value, e.g. I put a break point on each line and made sure I checked each one. This actually took a few days because I had to write export and import code and massage the data from Python to F#. See: How to determine type of nested data structures in Python? I also tried a variation where I replaced the F# list with Linked list, but found no increase in speed, e.g. LinkedList<Matrix<double>>. Was an interesting exercise.
If I understand correctly, let wX = weights |> List.map (fun w -> X |> List.map (fun (a, b, c) -> w * float a, w * float b, w * float c))
This is an alternate way to achieve this using Math.Net: https://numerics.mathdotnet.com/Matrix.html#Arithmetics
Nested array slicing
Let's say I have an array of vectors: """ simple line equation """ function getline(a::Array{Float64,1},b::Array{Float64,1}) line = Vector[] for i=0:0.1:1 vector = (1-i)a+(i*b) push!(line, vector) end return line end This function returns an array of vectors containing x-y positions Vector[11] > Float64[2] > Float64[2] > Float64[2] > Float64[2] . . . Now I want to seprate all x and y coordinates of these vectors to plot them with plotyjs. I have already tested some approaches with no success! What is a correct way in Julia to achive this?
You can broadcast getindex: xs = getindex.(vv, 1) ys = getindex.(vv, 2) Edit 3: Alternatively, use list comprehensions: xs = [v[1] for v in vv] ys = [v[2] for v in vv] Edit: For performance reasons, you should use StaticArrays to represent 2D points. E.g.: getline(a,b) = [(1-i)a+(i*b) for i=0:0.1:1] p1 = SVector(1.,2.) p2 = SVector(3.,4.) vv = getline(p1,p2) Broadcasting getindex and list comprehensions will still work, but you can also reinterpret the vector as a 2×11 matrix: to_matrix{T<:SVector}(a::Vector{T}) = reinterpret(eltype(T), a, (size(T,1), length(a))) m = to_matrix(vv) Note that this does not copy the data. You can simply use m directly or define, e.g., xs = #view m[1,:] ys = #view m[2,:] Edit 2: Btw., not restricting the type of the arguments of the getline function has many advantages and is preferred in general. The version above will work for any type that implements multiplication with a scalar and addition, e.g., a possible implementation of immutable Point ... end (making it fully generic will require a bit more work, though).
How to compute integral of an array
I am wondering if there is a way to perform integral on arrays in R. I have arrays S and R. I want to integrate them over pressure level (P) from 1000 to 850. How can I do this? . The S, R and P data are S<-structure(c(0.0011979939772106, 0.0011979939772106, 0.0011979939772106, 0.00122851820731487, 0.00122654890214685, 0.00122457959697883, 0.00124164690843498, 0.00123705186304294, 0.0012324568176509, 0.00133617355649982, 0.00133617355649982, 0.00133617355649982, 0.00138048292278021, 0.00137752896502818, 0.00137457500727616, 0.00140575567243643, 0.00139951953940438, 0.00139328340637232, 0.00139820666929237, 0.00139820666929237, 0.00139820666929237, 0.00151308280409338, 0.00150192340814128, 0.00149076401218919, 0.00155575108273376, 0.00154426346925366, 0.00153277585577356 ), .Dim = c(3L, 3L, 3L)) R<-structure(c(-15.1752538162522, -15.1929331135921, -15.2092524649828, -16.2142525214608, -16.2400914944961, -16.2604906837345, -17.2355719293295, -17.2641307942633, -17.2858899294509, -13.3842050011216, -13.4059641363092, -13.4250033795984, -14.3266475439352, -14.3361671655798, -14.3402470034274, -15.3466070058547, -15.3398072761085, -15.3262078166163, -10.7132711568418, -10.7350302920294, -10.7554294812678, -11.8379464568517, -11.8066677000195, -11.7726690512888, -13.8003484615847, -13.7187517046312, -13.6317151638807 ), .Dim = c(3L, 3L, 3L)) P<-c(1000,950,900,850) I tried the following and could not figure out how I can perform integral for an array. f <- function(x) {x} inr <- integrate(f,1000,850) #where f would be a function.
I am not entirely sure what you are asking, but there are two common answers when dealing with arrays and integration. The first one is a vectorization issue which can be dealt with by doing the following: IntFunc <- function(x,y) { sum(x-y) } IntFunc(1:5,c(0,0)) Warning message: In x - y : longer object length is not a multiple of shorter object length integrate(Vectorize(IntFunc,vectorize.args = 'x'), upper = 1000, lower = 850, y = R) 3803862 with absolute error < 4.2e-08 This question has been answered elsewhere on StackOverflow: How to pass vector to integrate function R, Integrate at each point of array
Clean mathematical notation of a for-loop
I am sorry if this doesn't really belong here but I'm looking for a way to describe the mathematical background of my code. Using numpy I sum two more dimensional arrays: a.shape = (10, 5, 2) b.shape = (5, 2) c = a + b c.shape = (10, 5, 2) Is there a pure mathematical notation for this (so WITHOUT indroducing for-loops or numpy conventions in my text)? What I'm trying to avoid is to have to write something like this: c_{1, y, z} = a_{1, y, z} + b_{y, z} c_{2, y, z} = a_{2, y, z} + b_{y, z} ... c_{10, y, z} = a_{10, y, z} + b_{y, z} Any thoughts? Edit: I'm using LaTeX for the documentation, so indexing is no problem. I'm currently using more or less the suggestion from Tobias. I was just hoping that there may be some other solution I haven't thought of.
Just write for . You find this form often in books on numerics like Numerical Recipes (e.g., page 57). If you have larger sections of code an alternative is to use pseudo-code.