Python 如何绘制scipy优化结果

Python 如何绘制scipy优化结果,python,numpy,scipy,maximize,Python,Numpy,Scipy,Maximize,我用函数f(x)=sin(x)对pythonscipy进行了优化,我想绘制结果。我该怎么做?我已经尝试了这个代码。但是我得到了这个错误:TypeError:只有length-1数组可以转换为Python标量 这是我的代码: '''Import Python math library''' import math import matplotlib.pyplot as plt '''try and except ImportError handler will be printing messag

我用函数f(x)=sin(x)对pythonscipy进行了优化,我想绘制结果。我该怎么做?我已经尝试了这个代码。但是我得到了这个错误:
TypeError:只有length-1数组可以转换为Python标量

这是我的代码:

'''Import Python math library'''
import math
import matplotlib.pyplot as plt
'''try and except ImportError handler will be printing message if you haven't install required python library'''
try:
    import scipy.optimize as opt
    import scipy
    from scipy.optimize import minimize
except ImportError:
    print "You must install Python scipy first before running this program"

try:
    import numpy as np
except ImportError:
    print "You must install Python numpy first before running this program"

'''function f(x) = sin(x)'''
def f(x):
    print x
    #return -x**(2)
    return math.sin(x)

'''
check here for fmin_l_bgfs_b docs : https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_l_bfgs_b.html#scipy.optimize.fmin_l_bfgs_b
and what params need to used.

or you can take a look at here : https://docs.scipy.org/doc/scipy/reference/optimize.html for other method and algorithm
'''
initial_guess = 1.0

minbound = -9
maxbound = 9

max_bounds_area = (minbound,maxbound)
max_x = opt.fmin_l_bfgs_b(lambda x: -f(x), initial_guess, bounds=[(max_bounds_area)],approx_grad=True)

# I want to plot the result. I try this but I get TypeError: only length-1 arrays can be converted to Python scalars
t = np.arange(minbound, maxbound, initial_guess)
s = f(t)
plt.plot(t, s)
plt.show()

math
库不能在
numpy数组上运行
,必须使用
numpy
中实现的函数

必须改变

return math.sin(x)


谢谢,它起作用了。但是我怎样才能使曲线平滑呢?有较小的初始猜测,是用来绘图的步骤。ie
initial\u guess=0.1
感谢它与
t=np.arange(minbound,maxbound,0.1)
一起工作。真的非常感谢。我需要等5分钟才能接受这个正确答案。
return np.sin(x)