Nagesh Joshi Nagesh Joshi - 3 months ago 30
Python Question

unhashable type: 'numpy.ndarray' for optimization

I was performing the optimization to find out the best fit line, using the scipy.optimize library, to a data set that I generated. But I am getting the error "unhashable type: 'numpy.ndarray'"

import numpy as np
import pandas as pd
import scipy.optimize as spo
import matplotlib.pyplot as plt

def error(data, line):
error=np.sum((data[:,1]-(line[0]*data[:,0]+line[1]))**2)
return error

def fit_line(data, error_func):
l=np.float32([0, np.mean(data[:,1])])
min_result=spo.minimize(error_func, l, args={data,}, method="SLSQP", options={"disp":True})
return min_result.x

if __name__=="__main__":
l_orig=np.float32([4,2])
xorig=np.linspace(0,10,21)
yorig=l_orig[1]*xorig + l_orig[0]

np.random.seed(788)
noise=np.random.normal(0, 3.0, yorig.shape)
data=np.asarray([xorig, yorig+noise]).T

result=fit_line(data, error)

Answer

The function scipy.optimize.minimize takes a tuple of extra arguments, not a set. Change:

min_result=spo.minimize(error_func, l, args={data,}, method="SLSQP", options={"disp":True})

to:

min_result=spo.minimize(error_func, l, args=(data,), method="SLSQP", options={"disp":True})