Python - Create matrix from a string - python

I have to create a matrix (or an array) from a string file like this:
>>>print Qval
[1*10**4,0,0,0],[0,1,0,0],[0,0,1*10**3,0], [0,0,0,1]
>>>print type(Qval)
<type 'str'>
I have to get the matrix this way, because in my Tkinter GUI I have to input the value like this (part of the interface: field label= default value):
Q-Matrix= [1*10**4,0,0,0],[0,1,0,0],[0,0,1*10**3,0],[0,0,0,1]
I get the Qval string from my interface like this:
Qval=vars[13].get()
Is there a proper way to do this?
Thanks.

>>> ast.literal_eval('[1e4, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1e3, 0], [0, 0, 0, 1]')
([10000.0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1000.0, 0], [0, 0, 0, 1])

you can use the built-in function eval like that:
a ="[1*10**4,0,0,0],[0,1,0,0],[0,0,1*10**3,0], [0,0,0,1]"
mat = eval(a)

Related

Kronecker product of 3 matrices using Python

Suppose that we have 2 2X2 numpy arrays:
X=np.array([[0,1],[1,0]])
and
I=np.array([[1,0],[0,1]])
Consider the Kronecker product
XX=X^X
where I have let the symbol ^ be the symbol for Kronecker product. This can easily be computed via the numpy.kron() function in python:
import numpy as np
kronecker_product = np.kron(X, X)
Now, suppose that we want to compute
XX=I^X^X
numpy.kron() only takes two arrays as arguments and expects them to be the same dimension. How can I perform this operation using numpy.kron() or other technique in python?
As with anything like this, try:
XX = np.kron(I, np.kron(X, X))
Output:
>>> XX
array([[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0]])
You can nest calls to kron any number of times. For example, for XX = A^B^C^D^E, use
XX = np.kron(A, np.kron(B, np.kron(C, np.kron(D, E))))
If you don't like the verbosity there, you could create an alias for np.kron:
k = np.kron
XX = k(A, k(B, k(C, k(D, E))))
Or, better yet, use reduce from the Python built-in module functools to do it in an even more readable fashion:
import functools as ft
lst = [A, B, C, D, E]
XX = ft.reduce(np.kron, lst)
Note: I tested all of this and it works perfectly.

How to label_binarize Multiclass in a specific class order

I have a list of ground truth labels:
yTrue = ['class2','classC','class3','class3','classA','classB','class2']
and a list of the possible classes (distinct, in custom order):
orderedClasses = ['classA','class2','classB','class3','classC']
I want to code the list in One-Vs-The-Rest for all possible classes.
Desired output:
[[0,1,0,0,0],[0,0,0,0,1],[0,0,0,1,0],[0,0,0,1,0],[1,0,0,0,0],[0,0,1,0,0],[0,1,0,0,0]]
I tried to use sklearn.preprocessing.label_binarize (doc) but the problem is it doesn't maintain my custom order for classes:
[[0,0,1,0,0],[0,0,0,0,1],[1,0,0,0,0],[1,0,0,0,0],[0,0,0,1,0],[0,1,0,0,0],[0,0,1,0,0]]
Looking for an Pythonic and efficient way to get the desired output
Simply pass orderedClasses as classes parameter
In [15]: label_binarize(yTrue, orderedClasses)
Out[15]:
array([[0, 1, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 0, 0]])

Make a 2-D array print 'nicer'

I have the following matrix generated:
matrix = [[0] * columns for i in range(rows)]
where the user defines the rows and columns in the main sequence.
Say the user entered the numbers such that rows = 5 and columns = 4. When I print the matrix, I will get the following:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Thats okay, but I would like to make it nicer, so that it would look like this:
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
I believe that you would need to use something like \n, but I'm having trouble as to how to implement it. Perhaps theres a built-in function alread that I don't know of? Any help would be appreciated.
def formattedPrint(matrix):
print "["
for i in matrix:
print(i)
print "]"
You can take a look at the pprint library built into Python. I use it in 2.7, but it is available in Python 3.

Printing list as table (row, col)

I'm trying to print a list as a table
The following code creates specified amount of rows and columns (in other words, it creates a list of a specified size).
finalgrid1 =[[0 for j in range(keyword_size)] #print rows (size of keyword)
for i in range(1 + new_grid_size)] #print column (size of ciphers)
print(finalgrid1)
The result printed is (when keyword_size = 3):
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Could someone show me how to print it in the following format.
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
I'm working on creating a Cipher encoder and decoder program as part of an assignment.
I've implemented the majority of it already - just stuck with printing it in the right format (as a table).
Btw, I am not asking you to apply any changes whatsoever, I only want to know how to print the list in the format of a table, that's all.
I appreciate your help
Try this, essentially prints each list out until there are none left to print
i = 0
while i < len(finalgrid1):
print finalgrid1[i]
i += 1
Stringify each list and join them together:
>>> grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>>
>>> print('\n'.join(str(x) for x in grid))
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

How to save 2D arrays (lists) in Python?

I need to save a 2D array representing a map in the game world to a configparser. The data looks like this:
[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
As an example.
I can obviously save the data but I can't convert it from a string back to a list after reading it back in...
I don't mind if I have to use a .txt file instead, by the way, and just read it in with the normal text file handler.
Python has a module for saving Python data called pickle. You can use that. From the docs:
The pickle module implements a fundamental, but powerful algorithm for
serializing and de-serializing a Python object structure. “Pickling”
is the process whereby a Python object hierarchy is converted into a
byte stream, and “unpickling” is the inverse operation, whereby a byte
stream is converted back into an object hierarchy. Pickling (and
unpickling) is alternatively known as “serialization”, “marshalling,”
or “flattening”, however, to avoid confusion, the terms used here
are “pickling” and “unpickling”.
Demo:
>>> import pickle
>>> data = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
>>> with open('C:/temp/pickle_test.data', 'wb') as f:
pickle.dump(data, f)
>>> with open('C:/temp/pickle_test.data', 'rb') as f:
new_data = pickle.load(f)
>>> new_data
[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
You can do it using a simple eval
>>> x="[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]"
>>> type(x);
<type 'str'>
>>> y=eval(x);
>>> print(y);
[[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]
>>>type(y);
<type 'list'>
It's a very quick and dirty solution, you should use more secure and good input files parsers (like pickle).
For the transformation of a string to a list you could do something like this:
myList = [x for x in "0,1,2,3".split(",")]
type(myList)
<type 'list'>
print myList
['0', '1', '2', '3']

Categories

Resources