Gurobi - Python Portfolio Optimization: Add stock concentration limit - gurobi

I'm trying to add a stock concentration limit to the Ipython Gurobi notebook below. I thought it would be [m.addConstr(portvars) <= 0.15, "limit")]; but I get an error message (see message below). Anyone have any idea how I could add a concentration limit?
https://anaconda.org/mcg/markowitz/notebook
TypeError: unsupported operand type(s) for -: 'bool' and 'NoneType'

Model.addConstr() takes a TempConstr object, so you probably want to write something like m.addConstr(sum(portvars) <= 0.15, "limit").

Related

unsupported operand type(s) for -: 'str' and 'str' - Implementation LimeTabularExplainer

my issue is that I get the following error
enter image description here
when I try to follow the implementation given in the notebook
https://github.com/klemag/PyconUS_2019-model-interpretability-tutorial/blob/master/02-interpretability_LIME-solution.ipynb
by Kevin Lemagnen.
I have used his suggested way of preprocessing the data and converting them to the format needed by the LIME XAI technique.
I have used the following helper function:
`def convert_to_lime_format(X, categorical_names, col_names=None, invert=False):
"""Converts data with categorical values as string into the right format
for LIME, with categorical values as integers labels.
It takes categorical_names, the same dictionary that has to be passed
to LIME to ensure consistency.
col_names and invert allow to rebuild the original dataFrame from
a numpy array in LIME format to be passed to a Pipeline or sklearn
OneHotEncoder
"""
# If the data isn't a dataframe, we need to be able to build it
if not isinstance(X, pd.DataFrame):
X_lime = pd.DataFrame(X, columns=col_names)
else:
X_lime = X.copy()
for k, v in categorical_names.items():
if not invert:
label_map = {
str_label: int_label for int_label, str_label in enumerate(v)
}
else:
label_map = {
int_label: str_label for int_label, str_label in enumerate(v)
}
X_lime.iloc[:, k] = X_lime.iloc[:, k].map(label_map)
return X_lime`
How can I fix this issue? Any help would be greatly appreciated.
I have already looked around on Stackoverflow and I have googled the TypeError and I found the following explanation:
The python error TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ occurs when you try to subtract a string from another that contains numbers in both strings. The TypeError is due to the operand type minus (‘-‘) is unsupported between str (string). Auto casting is not supported by python. You can subtract a number from a different number. If you try to subtract a string from another string that may contain a number, the error TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ will be thrown.
In python, an arithmetic operation can be used between valid numbers. For example, you can subtract a number from a different number. The integer can be subtracted from a float number. If you try to subtract a string from a string that contains a number, the error TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’ will be thrown.
Objects other than numbers can not be used in python substraction. The arithmetic subtract can be used only for numbers. If a number is stored as a string, it should be converted to an integer before subtracting it from each string. If you try to subtract a string to a string containing a number, the error TypeError: unsupported operand type(s) for +: ‘str’ and ‘str’ will be shown.
However, I was not able to resolve the problem.

Calculate pearson correlation between a tensor and a numpy array

I have managed to form a Dataframe of the predicted tensors(y_pred) which are of (459,1) after reshaping from (459,1,1) and i have the original y values in the other column which are also float32.
I would like to measure the pearson correlation between this 2 columns. but i am getting error:
pearsonr(df_pred['y_pred'],df_pred['y'])
unsupported operand type(s) for +: 'float' and 'tuple'
So i am not sure whether i can convert the tensor to numpy array and add that to the DataFrame. I have tried
predicted= tf.reshape(predicted, [459, 1])
predicted.numpy()
But it does not work. Any ideas?
I think you have to evaluate each tensor in the column to get it's value.
df['y_pred'] = df['y_pred'].apply(lambda x: x.eval())
How to get the value of a tensor?
predicted =predicted.numpy()
The above code worked at the end. As the values were appended under a for loop only writing
predicted.numpy()
did not work.

Pandas apply function is not resolving

Please view the Data Frame by clicking this image
Names=jobs[['Company Name']]
F = lambda x: x.split("\n")
Names.apply(F , axis=1)
AttributeError: 'Series' object has no attribute 'split'
When I run the following code, it works. Why am I facing this issue, I have never faced this kind of a problem before. PS: I got this data from scraping websites, unlike before. I am just hoping it has something to do with this
Names=jobs[['Company Name']]
F = lambda x: x.str.split("\n")
Names.apply(F , axis=1)
When I try it this why :
Ratings = jobs['Company Name'].apply(lambda x:x.split("\n")[1] , axis=1)
I get this error
TypeError: <lambda>() got an unexpected keyword argument 'axis'
You do not need the apply here, str.split is vectorized
jobs['Company Name'].str.split('\n')
should do the job.
I can not tell you why it had not worked before, but I can imagine it is due to the double brackets in [['Company Name']]. Single Brackets would collapse that to a Series while you keep the (2-dimensional Structure) of the Dataframe with the double brackets. See e.g. Python pandas: Keep selected column as DataFrame instead of Series for more details.

Errors using onehot_encode incorrect input format?

I'm trying to use the mx.nd.onehot_encode function, which should be straightforward, but I'm getting errors that are difficult to parse. Here is the example usage I'm trying.
m0 = mx.nd.zeros(15)
mx.nd.onehot_encode(mx.nd.array([0]), m0)
I expect this to return a 15 dim vector (at same address as m0) with only the first element set to 1. Instead I get the error:
src/ndarray/./ndarray_function.h:73: Check failed: index.ndim() == 1 && proptype.ndim() == 2 OneHotEncode only support 1d index.
Neither ndarray is of dimension 2, so why am I getting this error? Is there some other input format I should be using?
It seems that mxnet.ndarray.onehot_encode requires the target ndarray to explicitly have the shape [1, X].
I tried:
m0 = mx.nd.zeros((1, 15))
mx.nd.onehot_encode(mx.nd.array([0]), m0)
It reported no error.

Using spy() in Julia

I am trying to use spy(). But I am not getting the use of it right. I think my error has something to do with this: https://github.com/JuliaLang/julia/issues/2121
I have a 300x300 Array{Float64,2}
using PyPlot
pygui(true)
spy(I) # where I is my 300x300 array
and it gives me this error:
LoadError: PyError (:PyObject_Call) <type 'exceptions.TypeError'>
TypeError("object of type 'PyCall.jlwrap' has no len()",)
File "/home/ashley/.julia/v0.4/Conda/deps/usr/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3154, in plot
ret = ax.plot(*args, **kwargs)
File "/home/ashley/.julia/v0.4/Conda/deps/usr/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1539, in plot
zs = np.ones(len(xs)) * zs
I have tried specifying spy(I, zs=zeros(size(I)) but then I just get the error:
LoadError: ArgumentError: function spy does not accept keyword arguments
while loading In[260], in expression starting on line 13
Any ideas?
spy shows the non-zero elements. Apparently it doesn't show anything if there are no non-zero elements.
M = sprand(300, 300, 0.1) # generate a sparse matrix with density 0.1 of non-zeros
M = full(M)
spy(M)
works for me.