AttributeError: 'tuple' object has no attribute 'ravel' - python

I'm trying to solve two simultaneous nonlinear equations using the scipy.optimize.brute function
import numpy as np
import scipy.optimize as so
def root2d(x,a,b):
F1 = np.exp(-np.exp(-(x[0]+x[1]))) - x[1]*(b+x[0]**2)
F2 = x[0]*np.cos(x[1]) + x[1]*np.sin(x[0]) - a
return (F1,F2)
a = 0.5
b = 1
x0 = np.array([-0.1,0.1]) # initial guesses
rranges = (slice(-4,4,0.2),slice(-4,4,0.2))
print(so.brute(root2d,rranges,args=(a,b),finish=so.fmin))
I get an error that I don't understand: AttributeError: 'tuple' object has no attribute 'ravel'. What does this mean and how do I fix my code (if it's possible)?
Edit: full error message
Traceback (most recent call last):
File "<ipython-input-2-29b9507fcb99>", line 1, in <module>
runfile('.../test')
File "C:\WinPython\WinPython-64bit-3.5.2.3\python-3.5.2.amd64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\WinPython\WinPython-64bit-3.5.2.3\python-3.5.2.amd64\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "../test.py", line 111, in <module>
print(so.brute(root2d,rranges,args=(a,b),finish=so.fmin))
File "C:\WinPython\WinPython-64bit-3.5.2.3\python-3.5.2.amd64\lib\site-packages\scipy\optimize\optimize.py", line 2711, in brute
indx = argmin(Jout.ravel(), axis=-1)
AttributeError: 'tuple' object has no attribute 'ravel'

You return 2 variables F1 and F2 and reveive them using a single variable obj.(say) This is what is called a tuple obj,it is associated with 2 values, the values of F1 and F2. So, use index as you use in a list to get the value you want, in order.

Related

spatial regression in Python - read matrix from list

I have a following problem. I am following this example about spatial regression in Python:
import numpy
import libpysal
import spreg
import pickle
# Read spatial data
ww = libpysal.io.open(libpysal.examples.get_path("baltim_q.gal"))
w = ww.read()
ww.close()
w_name = "baltim_q.gal"
w.transform = "r"
Example above works. But I would like to read my own spatial matrix which I have now as a list of lists. See my approach:
ww = libpysal.io.open(matrix)
But I got this error message:
Traceback (most recent call last):
File "/usr/lib/python3.8/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/home/vojta/Desktop/INTERNET_HANDEL/ZASILKOVNA/optimal-delivery-branches/venv/lib/python3.8/site-packages/libpysal/io/fileio.py", line 90, in __new__
cls.__registry[cls.getType(dataPath, mode, dataFormat)][mode][0]
File "/home/vojta/Desktop/INTERNET_HANDEL/ZASILKOVNA/optimal-delivery-branches/venv/lib/python3.8/site-packages/libpysal/io/fileio.py", line 105, in getType
ext = os.path.splitext(dataPath)[1]
File "/usr/lib/python3.8/posixpath.py", line 118, in splitext
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not list
this is how matrix looks like:
[[0, 2, 1], [2, 0, 4], [1, 4, 0]]
EDIT:
If I try to insert my matrix into the GM_Lag like this:
model = spreg.GM_Lag(
y,
X,
w=matrix,
)
I got following error:
warn("w must be API-compatible pysal weights object")
Traceback (most recent call last):
File "/usr/lib/python3.8/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 2, in <module>
File "/home/vojta/Desktop/INTERNET_HANDEL/ZASILKOVNA/optimal-delivery-branches/venv/lib/python3.8/site-packages/spreg/twosls_sp.py", line 469, in __init__
USER.check_weights(w, y, w_required=True)
File "/home/vojta/Desktop/INTERNET_HANDEL/ZASILKOVNA/optimal-delivery-branches/venv/lib/python3.8/site-packages/spreg/user_output.py", line 444, in check_weights
if w.n != y.shape[0] and time == False:
AttributeError: 'list' object has no attribute 'n'
EDIT 2:
This is how I read the list of lists:
import pickle
with open("weighted_matrix.pkl", "rb") as f:
matrix = pickle.load(f)
How can I insert list of lists into spreg.GM_Lag ? Thanks
Why do you want to pass it to the libpysal.io.open method? If I understand correctly this code, you first open a file, then read it (and the read method seems to be returning a List). So in your case, where you already have the matrix, you don't need to neither open nor read any file.
What will be needed though is what w is supposed to look like here: w = ww.read(). If it is a simple matrix, then you can initialize w = matrix. If the read method also format the data a certain way, you'll need to do it another way. If you could describe the expected behavior of the read method (e.g. what does the input file contain, and what is returned), it would be useful.
As mentioned, as the data is formatted into a libpysal.weights object, you must build one yourself. This can supposedly be done with this method libpysal.weights.W. (Read the doc too fast).

how to create an undirected graph using a boolean list?

I have a list of zero's and one's.
(1's being higher than average and 0's being below average)
I am trying to make an undirected graph but I keep getting
test = (ustest[states] > final).astype(int)
test2 = test.unstack()#this is still a series
test3 = test2.tolist()#this is the series converted to a list
usmap = nx.Graph()
usmap = usmap.add_edges_from(test3)
I keep getting "TypeError: object of type 'int' has no len()" but I am unsure on what I am doing wrong.
I am trying to have to have this list be the edges in the graph.
EDIT
File "//anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "//anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/dshadow/Desktop/usstates.py", line 53, in
usmap = usmap.add_edges_from(test3)
File "//anaconda/lib/python3.6/site-packages/networkx/classes/graph.py", line 857, in add_edges_from
ne = len(e)
TypeError: object of type 'int' has no len()

Display a matrix with putting a common factor in sympy

I want to display a matrix with putting an extracted common factor on outside of the matrix after matrix calculation in sympy.
I wrote below code.
from sympy import *
a = symbols("a")
b = symbols("b")
A = Matrix([exp(I*a),exp(I*a)*exp(I*b)])
print simplify(A)
I got below output.
Matrix([
[ exp(I*a)],
[exp(I*(a + b))]])
However, I want to get below output.
exp(I*a)*Matrix([
[ 1],
[exp(I*b)]])
I tried collect(A,exp(I*a)) and got follow error.
Traceback (most recent call last):
File "<ipython-input-65-834f4c326df4>", line 1, in <module>
runfile('C:/Anaconda2/Programs/test/untitled44.py', wdir='C:/Anaconda2/Programs/test')
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Anaconda2/Programs/test/untitled44.py", line 14, in <module>
collect(A,exp(I*a))
File "C:\Anaconda2\lib\site-packages\sympy\simplify\simplify.py", line 451, in collect
if expr.is_Mul:
File "C:\Anaconda2\lib\site-packages\sympy\matrices\matrices.py", line 3084, in __getattr__
"%s has no attribute %s." % (self.__class__.__name__, attr))
AttributeError: MutableDenseMatrix has no attribute is_Mul.
I know a way to extract a common factor for a element of a matrix like follow link.
https://github.com/sympy/sympy/issues/8442
But it's not my desire.
How should I do?
I do not think Sympy provides a function for the task you want. However, you can do this manually, as per the method proposed in the accepted answer of a similar question asked in the Mathematica SE (link).
The idea is to extract the common factor of the polynomial elements via gcd and then use MatMul with the evaluate=False option in order to restrict Sympy from performing the scalar-matrix multiplication.
import sympy as sp
a, b = sp.symbols('a, b')
A = sp.Matrix([sp.exp(sp.I * a), sp.exp(sp.I * a) * sp.exp(sp.I * b)])
g = sp.gcd(tuple(A))
A_v2 = sp.MatMul(g,(A/g),evaluate = False)
print(A_v2)
exp(I*a)*Matrix([
[ 1],
[exp(I*b)]])

covariance of each key in a dictionary

I have a list, which is a set of tickers. For each ticker, I get the the daily return going back six months. I then want to compute the covariance between each ticker. I am having trouble with np.cov, here is my code to test COV:
newStockDict = {}
for i in newList_of_index:
a = Share(i)
dataB = a.get_historical(look_back_date, end_date)
stockData = pd.DataFrame(dataB)
stockData['Daily Return'] = ""
yList = []
for y in range(0,len(stockData)-1):
stockData['Daily Return'][y] = np.log(float(stockData['Adj_Close'][y])/float(stockData['Adj_Close'][y+1]))
yList = stockData['Daily Return'].values.tolist()
newStockDict[stockData['Symbol'][0]] = yList
g = (np.cov(pd.Series((newStockDict[newList_of_index[0]]))), pd.Series(((newStockDict[newList_of_index[1]]))))
return g
My error is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Udaya\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile
execfile(filename, namespace)
File "C:/Users/Udaya/Documents/Python Scripts/SR_YahooFinanceRead.py", line 150, in <module>
print CumReturnStdDev(stock_list)
File "C:/Users/Udaya/Documents/Python Scripts/SR_YahooFinanceRead.py", line 132, in CumReturnStdDev
g = (np.cov(pd.Series((newStockDict[newList_of_index[0]]))), pd.Series(((newStockDict[newList_of_index[1]]))))
File "C:\Users\Udaya\Anaconda\lib\site-packages\numpy\lib\function_base.py", line 1885, in cov
X -= X.mean(axis=1-axis, keepdims=True)
File "C:\Users\Udaya\Anaconda\lib\site-packages\numpy\core\_methods.py", line 66, in _mean
ret = umr_sum(arr, axis, dtype, out, keepdims)
TypeError: unsupported operand type(s) for +: 'numpy.float64' and 'str'
>>> TypeError: unsupported operand type(s) for +: 'numpy.float64' and 'str'
I've tried using pd.cov on a dataframe, then np.cov. Nothing works. Here I am actually appending the daily returns to a list, then to a dictionary, before I manually calculate an n by n covariance matrix. But I am unable to get np.cov to work.
Please help. The idea is I can easily construct a dataframe of N tickers, with each row being a daily return. but am unable to compute cov with said dataframe, thus this df-->list-->dict process.

Numpy array from pandas frames can't be count vectorized due to "'float' object has no attribute 'lower'" error

I have a pandas data frame that I am reading from a csv. It includes three columns, a subject line, and two numbers I am not using yet.
>>> input
0 1 2
0 Stress Free Christmas Gift They'll Love 0.010574 8
I have converted the list of subjects to a numpy array, and I want to use count vectorizer for naive bayes. When I do that, I get the following error.
>>> cv=CountVectorizer()
>>> subjects=np.asarray(input[0])
>>> cv.fit_transform(subjects)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 780, in fit_transform
vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary)
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 715, in _count_vocab
for feature in analyze(doc):
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 229, in <lambda>
tokenize(preprocess(self.decode(doc))), stop_words)
File "/Library/Python/2.7/site-packages/sklearn/feature_extraction/text.py", line 195, in <lambda>
return lambda x: strip_accents(x.lower())
AttributeError: 'float' object has no attribute 'lower'
These items should definitely all be strings. When I read the csv in with the csv library instead and created an array of that column, I didn't have any problems. Any ideas?

Categories

Resources