1

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)

1 Answer 1

4

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})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.