Run Matlab script from Python: TypeError: 'float' object is not iterable - python-2.7

Actually I have a problem when calling a Matlab script from Python.
import matlab.engine
import os
import random
import numpy as np
a=[str(random.randint(1,3)) for _ in range(3)]
print(a)
eng=matlab.engine.start_matlab()
eng.cd("/Users/dha/Documents/MATLAB/test-matlab/",nargout=0)
sr, state=eng.test_func()
print(sr)
print(state)
In fact I want to return "sr" which is a float and an array of integer "state", e.g. sr = 34.31 and state = [1,2,5]. The function test_func() work well on Matlab, but when I run this in Python from terminal (python test_matlab_engine.py) I received the following error:
Traceback (most recent call last):
File "test_matlab_engine.py", line 10, in <module>
sr, state=eng.mabuc_drl(a)
TypeError: 'float' object is not iterable
Anyone please give me the solution. Thank you so much in advance.

It seems that the result from MATLAB to Python has been cut off. If you have two parameters, you only get one which is the first parameter from the MATLAB. So, the question is how to get two or more parameters.
In a word, you should write this in your Python file:
re = eng.your_function_name(parameter1, parameter2, nargout=2)
where re contains two parameters which come from MATLAB.
You can find more information in the official documentation: Call MATLAB Functions from Python

Related

Storing pyplot object in variable

Please refer to the following code.
>>> p = plt.plot(year, rank)
>>> p.show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'show'
>>> plt.plot(year, rank)
[<matplotlib.lines.Line2D object at 0x7f3b56443890>]
>>> plt.show()
When I try to store plt in a variable p, it showing the AttributeError:
But when directly use plt.show(), it's working. I am not able to understand the difference.
I am using python 2.7 in Ubuntu 16.4, and running the program from terminal.
plt.plot(x,y) returns a list of Line2D objects. You store this list in a variable p. As the error tells you, 'list' object has no attribute 'show'. This can be taken literally, because show() is a function in the matplotlib.pyplot module and any normal python list does not even know about the existence of matplotlib.
You may of course still store the list in a variable, but in order to show the plot you need to use plt.show() independent of where you stored the return of any plotting commands
import matplotlib.pyplot as plt
p = plt.plot(x,y)
plt.show()

Invalid chart type given box

Here is my code
from pandas import read_csv
from pandas.tools.plotting import scatter_matrix
from matplotlib import pyplot
filename = 'iris.data.csv'
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = read_csv(filename, names=names)
print(dataset.shape)
print(dataset.head(20))
# Data visualizations
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
pyplot.show()
When i run above code. Then following error is shown
Traceback (most recent call last):
File "/media/k/UBUNTU2/Work and stuff/coding language/Python/Machine learning/exp.py", line 43, in <module>
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
File "/usr/local/lib/python2.7/dist-packages/pandas/tools/plotting.py", line 2090, in plot_frame
raise ValueError('Invalid chart type given %s' % kind)
ValueError: Invalid chart type given box
Any idea ? What should i do? Please help
Your pandas version (0.14) is already 3 years old. The "box" kind was introduced in version 0.15. Now we are at version 0.20.
The solution is thus to install a newer version of pandas in order to be able to use kind="box" in the plotting wrapper.
If you need to use version 0.14 you can get boxplot using the DataFrame.boxplot() method. The usage according to documentation would be:
df = DataFrame(rand(10,5))
plt.figure();
bp = df.boxplot()

Keras:Vgg16 -- Error in `decode_predictions'

I am trying to perform an image classification task using a pre-trained VGG16 model in Keras. The code I wrote, following the instructions in the Keras application page, is:
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
import numpy as np
model = VGG16(weights='imagenet', include_top=True)
img_path = './train/cat.1.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = model.predict(x)
(inID, label) = decode_predictions(features)[0]
which is quite similar to the code shown in this question already asked in the forum. But in spite of having the include_top parameter as True, I am getting the following error:
Traceback (most recent call last):
File "vgg16-keras-classifier.py", line 14, in <module>
(inID, label) = decode_predictions(features)[0]
ValueError: too many values to unpack
Any help will be deeply appreciated! Thanks!
It's because (according to a function definition which might be found here) a function decode_predictions returns a triple (class_name, class_description, score). This why it claims that there are too many values to unpack.

Python 2.7 and Textblob - TypeError: The `text` argument passed to `__init__(text)` must be a string, not <type 'list'>

Update: Issue resolved. (see comment section below.) Ultimately, the following two lines were required to transform my .csv to unicode and utilize TextBlob: row = [cell.decode('utf-8') for cell in row], and text = ' '.join(row).
Original question:
I am trying to use a Python library called Textblob to analyze text from a .csv file. Error I receive when I call Textblob in my code is:
Traceback (most recent call last): File
"C:\Users\Marcus\Documents\Blog\Python\Scripts\Brooks\textblob_sentiment.py",
line 30, in
blob = TextBlob(row) File "C:\Python27\lib\site-packages\textblob\blob.py", line 344, in
init
'must be a string, not {0}'.format(type(text)))TypeError: The text argument passed to __init__(text) must be a string, not
My code is:
#from __future__ import division, unicode_literals #(This was recommended for Python 2.x, but didn't help in my case.)
#-*- coding: utf-8 -*-
import csv
from textblob import TextBlob
with open(u'items.csv', 'rb') as scrape_file:
reader = csv.reader(scrape_file, delimiter=',', quotechar='"')
for row in reader:
row = [unicode(cell, 'utf-8') for cell in row]
print row
blob = TextBlob(row)
print type(blob)
I have been working through UTF/unicode issues. I'd originally had a different subject which I posed to this thread. (Since my code and the error have changed, I'm posting to a new thread.) Print statements indicate that the variable "row" is of type=str, which I thought indicated that the reader object had been transformed as required by Textblob. The source .csv file is saved as UTF-8. Can anyone provide feedback as to how I can get unblocked on this, and the flaws in my code?
Thanks so much for the help.
So maybe you can make change as below:
row = str([cell.encode('utf-8') for cell in row])

Use Python command line argument as function names and function values

Related to this question Command line arguments in python.
With the SYS module, how can I use a command line argument as a function name and function value, within my code - without importing some other module?
I'd like a solution that uses sys only. Also, please no variable-length params answers. Those are confusing. Assume that just the function name and one function variable are specified at the command line.
import sys
def reversal(aaa): return aaa[::-1]
a = sys.argv[1]
b = sys.argv[2]
print a(b)
At the command line
cpu_location$ python blah.py reversal 'abcdefg'
Traceback (most recent call last):
File "blah.py", line 8, in <module>
print a(b)
TypeError: 'str' object is not callable
I want to know how to make sys.argv[1] be considered a function name, thereby calling the function I have defined.
The other posts I see on this are a mash up of:
- dealing with C/C++ and adding some other module
- not using sys at all
- using the argv items as values for functions, and names of other files, instead of names of functions
Better than the eval solution would be:
a = globals()[sys.argv[1]]
a(b)
globals() returns a dictionary mapping global variables names to those global variables. So globals()['reversal'] evaluates to the reversal function.
It's safer than the eval function. With your approach you could do something like:
python blah.py 'lambda x: x+"hi"' foobar
Which would print foobarhi, which is unexpected because that's not a function name.
2 hours later, I find the answer. I think it's worth it to post it here in a very simple fashion.
Basiclaly there is no "function" data type in Python, but someone did mention a function eval, which is built-in. Execute python commands passed as strings in command line using python -c (No -c is needed for my own example)
The solution, is to change
a = sys.argv[1]
to
a = eval(sys.argv[1])
This will make the passed in word, reversal, be evaluated. It will evaluate to a function. Then the a(b) call will be a perfect call of a function on a string, like how it's defined. Output will be like:
cpu_location$ python blah.py reversal unquoted
detouqnu
cpu_location$ python blah.py reversal 'withquotes'
setouqhtiw
use google module: fire
pip install fire
Here's a simple example:
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
Then, from the command line, you can run:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30