How to convert a list or numpy array to a 1d torch tensor? - torch

I have a list (or, a numpy array) of float values. I want to create a 1d torch tensor that will contain all those values. I can create the torch tensor and run a loop to store the values.
But I want to know is there any way, I can create a torch tensor with initial values from a list or array? Also suggest me if there is any pythonic way to achieve this as I am working in pytorch.

These are general operations in pytorch and available in the documentation. PyTorch allows easy interfacing with numpy. There is a method called from_numpy and the documentation is available here
import numpy as np
import torch
array = np.arange(1, 11)
tensor = torch.from_numpy(array)

Related

How can OpenMDAO be used to solve a linear system of equations without inverting the A matrix?

I have a system of equations that is in the form:
Ax = b
Where A and b are a mixture of known states and state rates derived from earlier components and x is a vector of four yet unknown state rates. I've used Matlab to linearise the problem, all I need to do now is to create some components to find x. However, the inverse of A is large in terms of the number of variables in each index, so I can't just turn these into a straightforward linear equation. Could someone suggest a route to go?
I don't fully understand what you mean by "the inverse of A is large in terms of the number of variables in each index", however I think mean that the inverse of A is to larger and dense to compute and store in memory.
OpenMDAO or not, When you run into this situation you are forced to use an iterative linear solver such as gmres. So that is broadly the approach that is needed here too.
OpenMDAO does have a LinearSystemComponent that you can use as a rough blueprint here. However, it does compute a factorization and store it which is not what you want. Regardless, it gives you the blueprint for how to represent a linear system as an implicit component in OpenMDAO.
Broadly, you have to think of defining a linear residual:
R = Ax-b = 0
Your component will have two inputs A and b, and and one output x.
The two key methods here are apply_nonlinear and solve_nonlinear. I realize that the word nonlinear in the method names is confusing. OpenMDAO assumes that the analysis is nonlinear. In your case it happens to be linear, but you use the nonlinear methods all the same.
I will assume that, although you can't compute/store [A] inverse you can compute/store A (perhaps in a sparse format). In that case you might pass the sparse data array of [A] as the input and fill the sparse matrix as needed from that.
the apply_nonlinear method would look like this:
def apply_nonlinear(self, inputs, outputs, residuals):
"""
R = Ax - b.
Parameters
----------
inputs : Vector
unscaled, dimensional input variables read via inputs[key]
outputs : Vector
unscaled, dimensional output variables read via outputs[key]
residuals : Vector
unscaled, dimensional residuals written to via residuals[key]
"""
residuals['x'] = inputs['A'].dot(outputs['x']) - inputs['b']
The key to your question is really the solve_nonlinear method. It would look something like this (using scipy gmres):
def solve_nonlinear(self, inputs, outputs):
"""
Use numpy to solve Ax=b for x.
Parameters
----------
inputs : Vector
unscaled, dimensional input variables read via inputs[key]
outputs : Vector
unscaled, dimensional output variables read via outputs[key]
"""
x, exitCode = gmres(inputs['A'], inputs['b'])
outputs['x'] = x

TensorFlow apply a function to each row of a matrix variable

Hi I'm a newbie to Tensorflow. What I want to do is something like this in R:
mat = tf$Variable(matrix(1:4, nrow = 2))
apply(mat, 1, cumprod)
Is this do-able in Tensorflow, either in Python API or R tensorflow package? Thanks!
EDIT: tf$cumprod is actually what I want.
The TensorFlow Python API includes the tf.map_fn(fn, elems) higher-order operator, which allows you to specify a (Python) function fn that will be applied to each slice of elems in the 0th dimension (i.e. to each row if elems is a matrix).
Note that, while tf.map_fn() is very general, it may be more efficient to use specialized ops that either broadcast their arguments on one or more dimensions (e.g. tf.multiply()), or reduce in parallel across one or more dimensions (e.g. tf.reduce_sum()). However, tf.map_fn() is useful when there is no built-in operator to do what you want.

difference between exponential and log functions for numpy and math

This sounds like a naive question, but I can't figure out why there are two instances of functions like e, log etc., one for each numpy and math. For example numpy.e and math.e give me exactly the same result 2.71828....... What's the reason for this duplication?
numpy functions are called ufunc, you can use them on numpy array:
>>> import numpy
>>> numpy.exp (numpy.array([1, 2, 3]))
array([ 2.71828183, 7.3890561 , 20.08553692])
math functions are standard function (part of the standard python library), so they can be used only on standard types (such as int or float).
numpy functions are much more powerful than the math ones (when working on vector / matrix / etc.), but numpy is not a standard library.
If you check the type of the exp function, you get the following:
>>> type(numpy.exp)
numpy.ufunc
>>> type(math.exp)
builtin_function_or_method
Where you can see that numpy has defined its own exp function, whereas the math.exp function is builtin.
You cannot use them interchangeably at will: numpy.exp will work where math.exp works, but the inverse is not true (math.exp([1, 2, 3]) fails).

Convert a genetic optimiser into a Driver

I already have my component with the function I want to optimise. However, OpenMDAO Alpha 1.0 does not contain (to my knowledge) a wrapper for a genetic optimiser. I have written my own, and would now like to make it a Driver. I am a bit lost here, can I ask for any guidance?
Thank you!
You're correct that OpenMDAO doesn't have a genetic optimizer yet. You could use NSGAII from the pyopt library, but since you have one you want to use, writing your own driver should be fairly straightforward. The easiest example to follow would be our scipy wrapper for its optimizers. Your wrapper would have to look something like this:
from openmdao.core.driver import Driver
class GeneticOptimizer(Driver):
def __init__(self):
super(GeneticOptimizer, self).__init__()
#some stuff to setup your genetic optimizer here
def run(self, problem):
"""function called to kick off the optimization
Args
----
problem : `Problem`
Our parent `Problem`.
"""
#NOTE: you'll use these functions to build your optimizer
#to execute the model
problem.root.solve_nonlinear()
#function to set values to the design variables
self.set_param(var_name, value)

How to compute the volume of an unstructured mesh using TVTK and Python?

I'm trying to calculate the volume of an unstructured grid using mayavi and tvtk. My idea was to tetrahedronalize the Point cloud by means of the Delaunay3d-Filter. Then I Need to somehow extract the tetrahedra from this dataset while ignoring other cell-types such as lines and triangles.
But how can i accomplish this? My Python code so far Looks as follows:
import numpy as np
from mayavi import mlab
x, y, z = np.random.random((3, 100))
data = x**2 + y**2 + z**2
src = mlab.pipeline.scalar_scatter(x, y, z, data)
field = mlab.pipeline.delaunay3d(src)
Can i use the field-object to retrieve the polyhedras Vertices?
Thanks in advance.
frank.
Is this the best way to go about it? scipy.spatial has delaunay functionality as well. Having recently worked with both myself, I would note that scipy is a much lighter dependency, easier to use, and better documented. Note that either method will work on the convex hull of the pointcloud, which may not be what you want. the scipy version also easily allows you to compute the boundary primitives as well, amongst other things, which may be useful for further processing.

Resources