scipy curve_fit error: Result from function call is not a proper array of floats - scipy

I have an [x,y] dataset and I would like to fit a function to it.
This are x and y
parang = np.array([ 61.1725 , 62.140625, 62.93275 , 63.701625, 65.89225 ,
66.476875, 68.33525 , 68.902375, 72.03975 , 72.590375,
73.144125, 73.670625, 80.36525 , 80.80275 , 87.505375,
87.90375 , 100.557875, 100.8915 ])
q = np.array([-0.03699417, -0.03451252, -0.03851238, -0.0393034 , -0.04059193,
-0.03941371, -0.04206476, -0.04153004, -0.04721763, -0.04667099,
-0.03996427, -0.03872865, -0.05054322, -0.0466561 , -0.05476921,
-0.05274144, -0.0474299 , -0.04974607])
and then I want to fit a function to the data that goes as follows:
def fq(x,bq,cuq):
qval = bq*stndqu[0]*np.cos(np.radians(2*x))+cuq*stndqu[1]*np.sin(np.radians(2*x))
print qval
print qval.dtype
return qval
where 'bq,cuq' are the parameter I need to fit and stndqu are global parameters I obtain as:
stnd = input(r'P ($\%$) and $\theta$ of pol. standard? (as tuple)')
p = stnd[0]/100.
ang = np.radians(stnd[1])
x,y = sympy.symbols('x y')
stndqu = sympy.solve([sympy.sqrt(x**2+y**2)-p,(0.5*sympy.atan(y/x))-ang],[x,y])[1]
and P and theta are 2.73 and 95. The stndqu[0] and stndqu[1] I get out from that block are
0.0272334985720932 and 0.00190435173321445
To find the parameters 'bq' and 'cuq' of the function that fit my data I do:
qpopt,pconv = scio.curve_fit(fq, parang, q)
and here's the result:
[-0.0129614827538107 -0.0137658898997091 -0.0144124082012406
-0.0150294169782742 -0.0167265263727253 -0.0171633151430064
-0.0185034265676582 -0.0188971421096823 -0.0209373417940197
-0.0212701779430718 -0.0215969783128203 -0.0219002154908251
-0.0250793309165333 -0.0252411052388773 -0.0269646924974054
-0.0270214005655701 -0.0260909416985902 -0.0259956074319825]
object
[-0.0129614827538107 -0.0137658898997091 -0.0144124082012406
-0.0150294169782742 -0.0167265263727253 -0.0171633151430064
-0.0185034265676582 -0.0188971421096823 -0.0209373417940197
-0.0212701779430718 -0.0215969783128203 -0.0219002154908251
-0.0250793309165333 -0.0252411052388773 -0.0269646924974054
-0.0270214005655701 -0.0260909416985902 -0.0259956074319825]
object
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: array cannot be safely cast to required type
---------------------------------------------------------------------------
error Traceback (most recent call last)
/Users/mj/Documents/NACO/VLT/DataReduction/<ipython-input-57-cac353117232> in <module>()
----> 1 qpopt,pconv = scio.curve_fit(fq, parang, q)
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/optimize/minpack.pyc in curve_fit(f, xdata, ydata, p0, sigma, **kw)
408 # Remove full_output from kw, otherwise we're passing it in twice.
409 return_full = kw.pop('full_output', False)
--> 410 res = leastsq(func, p0, args=args, full_output=1, **kw)
411 (popt, pcov, infodict, errmsg, ier) = res
412
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/optimize/minpack.pyc in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag, warning)
268 if (maxfev == 0):
269 maxfev = 200*(n+1)
--> 270 retval = _minpack._lmdif(func,x0,args,full_output,ftol,xtol,gtol,maxfev,epsfcn,factor,diag)
271 else:
272 if col_deriv:
error: Result from function call is not a proper array of floats.
I tried specifying the type of the qval element making it
def fq(x,bq,cuq):
qval = np.array(
bq*stndqu[0]*np.cos(np.radians(2*x))+cuq*stndqu[1]*np.sin(np.radians(2*x)),
dtype=float)
and then the result changes to:
qpopt = scio.curve_fit(fq, parang, q)
[-0.01296148 -0.01376589 -0.01441241 -0.01502942 -0.01672653 -0.01716332
-0.01850343 -0.01889714 -0.02093734 -0.02127018 -0.02159698 -0.02190022
-0.02507933 -0.02524111 -0.02696469 -0.0270214 -0.02609094 -0.02599561]
float64
[-0.01296148 -0.01376589 -0.01441241 -0.01502942 -0.01672653 -0.01716332
-0.01850343 -0.01889714 -0.02093734 -0.02127018 -0.02159698 -0.02190022
-0.02507933 -0.02524111 -0.02696469 -0.0270214 -0.02609094 -0.02599561]
float64
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: array cannot be safely cast to required type
---------------------------------------------------------------------------
error Traceback (most recent call last)
/Users/mj/Documents/NACO/VLT/DataReduction/<ipython-input-50-1f4d3764f7ae> in <module>()
----> 1 qpopt = scio.curve_fit(fq, parang, q)
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/optimize/minpack.pyc in curve_fit(f, xdata, ydata, p0, sigma, **kw)
408 # Remove full_output from kw, otherwise we're passing it in twice.
409 return_full = kw.pop('full_output', False)
--> 410 res = leastsq(func, p0, args=args, full_output=1, **kw)
411 (popt, pcov, infodict, errmsg, ier) = res
412
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/optimize/minpack.pyc in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag, warning)
268 if (maxfev == 0):
269 maxfev = 200*(n+1)
--> 270 retval = _minpack._lmdif(func,x0,args,full_output,ftol,xtol,gtol,maxfev,epsfcn,factor,diag)
271 else:
272 if col_deriv:
error: Result from function call is not a proper array of floats.
So no progress...
Can someone tell me where is this going wrong?
Thank you very much in advance!
M.

Since stndqu is the result of a call to sympy.solve, it is a symbolic object still. The numbers that you see when printing qval from within your function are probably sympy floats (and thus generic objects to numpy). You should convert stndqu into a numpy array before using it with scipy.curve_fit:
stndqun = numpy.array([sympy.N(i) for i in stndqu])

Related

AttributeError: 'Index' object has no attribute 'index'

I have saved & loaded a simple XGBClassifier(random_sate = 100) model, trained on Heart Disease prediction dataset(target variable mapped to 0s & 1s). I am trying to create a dtreeviz plot for the same:
from dtreeviz.trees import *
viz = dtreeviz(loaded_model, X_train, y_train, tree_index = 10,feature_names = X_train.columns,
class_names = ['Absence', 'Presence'], target_name = 'Heart Disease')
viz.view()
However, I am getting the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-18-2a3024516ed1> in <module>
1 from dtreeviz.trees import *
----> 2 viz = dtreeviz(loaded_model, X_train, y_train, tree_index = 10, feature_names = X_train.columns,
3 class_names = ['Absence', 'Presence'], target_name = 'Heart Disease')
4 viz.view()
~\anaconda3\lib\site-packages\dtreeviz\trees.py in dtreeviz(tree_model, x_data, y_data, feature_names, target_name, class_names, tree_index, precision, orientation, instance_orientation, show_root_edge_labels, show_node_labels, show_just_path, fancy, histtype, highlight_path, X, max_X_features_LR, max_X_features_TD, depth_range_to_display, label_fontsize, ticks_fontsize, fontname, title, title_fontsize, colors, cmap, scale)
816 if shadow_tree.is_classifier():
817 nbins = get_num_bins(histtype, n_classes)
--> 818 node_heights = shadow_tree.get_split_node_heights(X_data, y_data, nbins=nbins)
819
820 internal = []
~\anaconda3\lib\site-packages\dtreeviz\models\shadow_decision_tree.py in get_split_node_heights(self, X_train, y_train, nbins)
273 for node in self.internal:
274 # print(node.feature_name(), node.id)
--> 275 X_feature = X_train[:, node.feature()]
276 overall_feature_range = (np.min(X_feature), np.max(X_feature))
277 # print(f"range {overall_feature_range}")
~\anaconda3\lib\site-packages\dtreeviz\models\shadow_decision_tree.py in feature(self)
506 """Returns feature index used at this node"""
507
--> 508 return self.shadow_tree.get_node_feature(self.id)
509
510 def feature_name(self) -> (str, None):
~\anaconda3\lib\site-packages\dtreeviz\models\xgb_decision_tree.py in get_node_feature(self, id)
76 feature_name = self._get_nodes_values("Feature")[id]
77 try:
---> 78 return self.feature_names.index(feature_name)
79 except ValueError as error:
80 return self.__class__.NO_FEATURE
AttributeError: 'Index' object has no attribute 'index'
I have been trying resolve this since yesterday, however, I can not find any solution.
Kindly help!
Thanks,
Neel

Python Jupyter Notebook scipy

For a long time I was able to add data and fit, then plot the curve with data. But recently I get this:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-6-6f645a2744bc> in <module>
1 poland = prepare_data(europe_data, 'Poland')
----> 2 plot_all(poland, max_y=400000)
3 poland
~/Pulpit/library.py in plot_all(country, max_x, max_y)
43 def plot_all(country, max_x = 1000, max_y = 500000):
44
---> 45 parameters_logistic = scipy.optimize.curve_fit(func_logistic, country['n'], country['all'])[0]
46 parameters_expo = scipy.optimize.curve_fit(func_expo, country['n'], country['all'])[0]
47
/usr/local/lib64/python3.6/site-packages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
787 cost = np.sum(infodict['fvec'] ** 2)
788 if ier not in [1, 2, 3, 4]:
--> 789 raise RuntimeError("Optimal parameters not found: " + errmsg)
790 else:
791 # Rename maxfev (leastsq) to max_nfev (least_squares), if specified.
RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.
Here are all Python Jupyter Notebook files: https://files.fm/u/zj7cc6ne#sign_up
How to solve this?
scipy.optimize.curve_fit takes a keyword argument p0.
Initial guess for the parameters (length N). If None, then the initial
values will all be 1 (if the number of parameters for the function can
be determined using introspection, otherwise a ValueError is raised).
If the defaults 1 are too far of from the result the algorithm may not converge. Try to put some values that make sense for your problem.

Mismatch in Input Shape of tf.keras model

I am getting a mismatch in input shape of a tf.keras model. The code block is given below with the stack trace. I am using hub.keraslayer as my first layer. The model is being made for being trained using Tensor Flow Federated (TFF). The input to the model are variable length strings. Kindly suggest a way out.
#Making a Tensorflow Model
from tensorflow import keras
def create_keras_model():
encoder = hub.load("https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1")
return tf.keras.models.Sequential([
hub.KerasLayer(encoder, input_shape=[],dtype=tf.string,trainable=True),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(16, activation='relu'),
keras.layers.Dense(1, activation='sigmoid'),
])
def model_fn():
# We _must_ create a new model here, and _not_ capture it from an external
# scope. TFF will call this within different graph contexts.
keras_model = create_keras_model()
return tff.learning.from_keras_model(
keras_model,
input_spec=preprocessed_example_dataset.element_spec,
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.Accuracy()])
iterative_process = tff.learning.build_federated_averaging_process(
model_fn,
client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-
packages/tensorflow/python/ops/resource_variable_ops.py:1817: calling
BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with
constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-
packages/tensorflow/python/ops/resource_variable_ops.py:1817: calling
BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with
constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
WARNING:tensorflow:Model was constructed with shape (None,) for input
Tensor("keras_layer_input:0", shape=(None,), dtype=string), but it was called on an input
with incompatible shape (None, None).
WARNING:tensorflow:Model was constructed with shape (None,) for input
Tensor("keras_layer_input:0", shape=(None,), dtype=string), but it was called on an input
with incompatible shape (None, None).
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-27-68fa27e65b7e> in <module>()
3 model_fn,
4 client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
----> 5 server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))
18 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in
wrapper(*args, **kwargs)
966 except Exception as e: # pylint:disable=broad-except
967 if hasattr(e, "ag_error_metadata"):
--> 968 raise e.ag_error_metadata.to_exception(e)
969 else:
970 raise
ValueError: in user code:
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/federated_averaging.py:91 __call__ *
num_examples_sum = dataset.reduce(
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/model_utils.py:152 forward_pass *
self._model.forward_pass(batch_input, training), model_lib.BatchOutput)
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/keras_utils.py:391 forward_pass *
return self._forward_pass(batch_input, training=training)
/usr/local/lib/python3.6/dist-
packages/tensorflow_federated/python/learning/keras_utils.py:359 _forward_pass *
predictions = self._keras_model(inputs, training=training)
/usr/local/lib/python3.6/dist-packages/tensorflow_hub/keras_layer.py:222 call *
result = f()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/saved_model/load.py:486
_call_attribute **
return instance.__call__(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/def_function.py:580 __call__
result = self._call(*args, **kwds)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/def_function.py:618 _call
results = self._stateful_fn(*args, **kwds)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2419 __call__
graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2735
_maybe_define_function
*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2238
canonicalize_function_inputs
self._flat_input_signature)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/function.py:2305
_convert_inputs_to_signature
format_error_message(inputs, input_signature))
ValueError: Python inputs incompatible with input_signature:
inputs: (
Tensor("batch_input:0", shape=(None, None), dtype=string))
input_signature: (
TensorSpec(shape=(None,), dtype=tf.string, name=None))

Sympy .coeff_all() returned list is not readable by scipy

I have question about the data type of the result returned by Sympy Poly.all_coeffs(). I have started to use Sympy just recently.
My Sympy transfer function is following:
Then I run this code:
n,d = fraction(Gs)
num = Poly(n,s)
den = Poly(d,s)
num_c = num.all_coeffs()
den_c = den.all_coeffs()
I get:
Then I run this code:
from scipy import signal
#nu = [5000000.0]
#de = [4.99, 509000.0]
nu = num_c
de = den_c
sys = signal.lti(nu, de)
w,mag,phase = signal.bode(sys)
plt.plot(w/(2*np.pi), mag)
and the result is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-131-fb960684259c> in <module>
4 nu = num_c
5 de = den_c
----> 6 sys = signal.lti(nu, de)
But if I use those commented line 'nu' and 'de' straight python lists instead, the program works. So what is wrong here?
Why did you just show a bit the error? Why not the full message, maybe even the full traceback!
In [60]: sys = signal.lti(num_c, den_c)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-60-21f71ecd8884> in <module>
----> 1 sys = signal.lti(num_c, den_c)
/usr/local/lib/python3.6/dist-packages/scipy/signal/ltisys.py in __init__(self, *system, **kwargs)
590 self._den = None
591
--> 592 self.num, self.den = normalize(*system)
593
594 def __repr__(self):
/usr/local/lib/python3.6/dist-packages/scipy/signal/filter_design.py in normalize(b, a)
1609 leading_zeros = 0
1610 for col in num.T:
-> 1611 if np.allclose(col, 0, atol=1e-14):
1612 leading_zeros += 1
1613 else:
<__array_function__ internals> in allclose(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in allclose(a, b, rtol, atol, equal_nan)
2169
2170 """
-> 2171 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2172 return bool(res)
2173
<__array_function__ internals> in isclose(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in isclose(a, b, rtol, atol, equal_nan)
2267 y = array(y, dtype=dt, copy=False, subok=True)
2268
-> 2269 xfin = isfinite(x)
2270 yfin = isfinite(y)
2271 if all(xfin) and all(yfin):
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Now look at the elements of the num_c list (same for den_c):
In [55]: num_c[0]
Out[55]: 500000.000000000
In [56]: type(_)
Out[56]: sympy.core.numbers.Float
The scipy code is doing numpy testing on the inputs. So it's first turned the lists into arrays:
In [61]: np.array(num_c)
Out[61]: array([500000.000000000], dtype=object)
This array contains sympy object(s). It can't cast that to numpy float with 'safe'. But an explicit astype uses unsafe as the default:
In [63]: np.array(num_c).astype(float)
Out[63]: array([500000.])
So lets convert both lists into valid numpy float arrays:
In [64]: sys = signal.lti(np.array(num_c).astype(float), np.array(den_c).astype(float))
In [65]: sys
Out[65]:
TransferFunctionContinuous(
array([100200.4008016]),
array([1.00000000e+00, 1.02004008e+05]),
dt: None
)
Conversion in a list comprehension also works:
sys = signal.lti([float(i) for i in num_c],[float(i) for i in den_c])
You likely need to conver sympy objects to floats / lists of floats.

Autoencoder in fastai

I'm trying to build an autoencoder with fast.ai version 1.0.52 and struggling with how to set labels to be equal to original images. I was
following this blog post: https://alanbertl.com/autoencoder-with-fast-ai/
I replaced ImageItemList in the original code with ImageList since it was changed in the latest fastai versions.
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.imports import *
from fastai.vision import *
from fastai.data_block import *
from fastai.basic_train import *
import pandas as pd
x = np.random.randint(256, size=(1000, 16384))
x = x/255
x = x.reshape(-1,128,128)
x = np.stack([x,x,x],1)
x.shape
class ArraysImageList(ImageList,FloatList):
def __init__(self, items:Iterator, log:bool=False, **kwargs):
if isinstance(items, ItemList):
items = items.items
super(FloatList,self).__init__(items,**kwargs)
def get(self,i):
return Tensor(super(FloatList,self).get(i).astype('float32'))
x_il = ArraysImageList(x)
x_ils = x_il.split_by_rand_pct()
lls = x_ils.label_from_lists(x_ils.train, x_ils.valid)
Here's the error message I get.
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-33-cbada9e18af9> in <module>
----> 1 lls = x_ils.label_from_lists(x_ils.train, x_ils.valid)
~/.local/lib/python3.6/site-packages/fastai/data_block.py in label_from_lists(self, train_labels, valid_labels, label_cls, **kwargs)
484 self.valid = self.valid._label_list(x=self.valid, y=self.train.y.new(valid_labels, **kwargs))
485 self.__class__ = LabelLists
--> 486 self.process()
487 return self
488
~/.local/lib/python3.6/site-packages/fastai/data_block.py in process(self)
520 "Process the inner datasets."
521 xp,yp = self.get_processors()
--> 522 for ds,n in zip(self.lists, ['train','valid','test']): ds.process(xp, yp, name=n)
523 #progress_bar clear the outputs so in some case warnings issued during processing disappear.
524 for ds in self.lists:
~/.local/lib/python3.6/site-packages/fastai/data_block.py in process(self, xp, yp, name)
683 def process(self, xp:PreProcessor=None, yp:PreProcessor=None, name:str=None):
684 "Launch the processing on `self.x` and `self.y` with `xp` and `yp`."
--> 685 self.y.process(yp)
686 if getattr(self.y, 'filter_missing_y', False):
687 filt = array([o is None for o in self.y.items])
~/.local/lib/python3.6/site-packages/fastai/data_block.py in process(self, processor)
73 if processor is not None: self.processor = processor
74 self.processor = listify(self.processor)
---> 75 for p in self.processor: p.process(self)
76 return self
77
~/.local/lib/python3.6/site-packages/fastai/data_block.py in process(self, ds)
334
335 def process(self, ds):
--> 336 if self.classes is None: self.create_classes(self.generate_classes(ds.items))
337 ds.classes = self.classes
338 ds.c2i = self.c2i
~/.local/lib/python3.6/site-packages/fastai/data_block.py in generate_classes(self, items)
391 for c in items: classes = classes.union(set(c))
392 classes = list(classes)
--> 393 classes.sort()
394 return classes
395
RuntimeError: bool value of Tensor with more than one value is ambiguous
Ultimately, I want to read images using a dataframe with image paths. So I also tried the following:
import sklearn
cv = sklearn.model_selection.GroupKFold(n_splits=5)
train_inds, valid_inds = next(cv.split(iso_image_df.group, groups=iso_image_df.group))
img_lists = (ImageList.from_df(iso_image_df, resized_img_path, cols=0).split_by_idxs(train_inds, valid_inds))
src = img_lists.label_from_lists(img_lists.train, img_lists.valid)
data = (src.databunch(bs = 32).normalize(imagenet_stats))
data.show_batch(rows=3, figsize=(10, 10))
Here I get the following error message:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-146-2514de511e64> in <module>
----> 1 data.show_batch(rows=3, figsize=(10, 10))
~/.local/lib/python3.6/site-packages/fastai/basic_data.py in show_batch(self, rows, ds_type, reverse, **kwargs)
190 #TODO: get rid of has_arg if possible
191 if has_arg(self.train_ds.y.reconstruct, 'x'):
--> 192 ys = [self.train_ds.y.reconstruct(grab_idx(y, i), x=x) for i,x in enumerate(xs)]
193 else : ys = [self.train_ds.y.reconstruct(grab_idx(y, i)) for i in range(n_items)]
194 self.train_ds.x.show_xys(xs, ys, **kwargs)
~/.local/lib/python3.6/site-packages/fastai/basic_data.py in <listcomp>(.0)
190 #TODO: get rid of has_arg if possible
191 if has_arg(self.train_ds.y.reconstruct, 'x'):
--> 192 ys = [self.train_ds.y.reconstruct(grab_idx(y, i), x=x) for i,x in enumerate(xs)]
193 else : ys = [self.train_ds.y.reconstruct(grab_idx(y, i)) for i in range(n_items)]
194 self.train_ds.x.show_xys(xs, ys, **kwargs)
~/.local/lib/python3.6/site-packages/fastai/data_block.py in reconstruct(self, t, x)
89 def reconstruct(self, t:Tensor, x:Tensor=None):
90 "Reconstruct one of the underlying item for its data `t`."
---> 91 return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t)
92
93 def new(self, items:Iterator, processor:PreProcessors=None, **kwargs)->'ItemList':
AttributeError: 'Image' object has no attribute 'reconstruct'
Any help is highly appreciated!
The lls are being used to create the databunch.
I've looked at it and given the API change in fastai libs I created the databunch without using the lls that were causing the error:
bs = 64
db = (ImageImageList.from_folder(mnist)
.split_by_folder()
.label_from_func(get_y_fn)
.databunch(bs=bs,num_workers=4))
EDIT: you'll need the get_y_fn; it is very simply defined
def get_y_fn(x): return x
the lls aren't used for anything else anyway
This should fix your problem, let me know if this worked for you.