花生酥干 2023-08-16 10:40 采纳率: 33.3%
浏览 8

python不支持操作数

代码:

# -*-coding: utf-8 -*一

_author_=' zengxin. '
_date_ ='2023/8/16 上午9:50'
_product_='PyCharm'
_filename_ ='gradient.descent.py'



#插包

import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt


# 构建元素图像
def f1(x):
    return 0.5*(x-0.25)**2
def h(x):
    return 0.5*2*(x-0.25)

# 梯度下降法
GD_x =[]
GD_y =[]
x = 2
alpha = 0.5
f_change = f1(x)
f_current = f_change
GD_x.append(x)
GD_y.append(f_current )

# 迭代次数
iter_num = 0

while f_change > 1e-10 and iter_num <100 :
    iter_num +=1
    x = x- alpha * h(x)
    temp = f1(x)
    f_change = np.abs(f_current - temp)
    f_current = temp
    GD_x.append(x)
    GD_y.append(f_current)
print(u'结果:(%.5f, %.5f)' %(x,f_current))
print(u'迭代次数(%.5f)'%(iter_num ))
print(GD_x)

# 构建数据
x = np.arange(-4,4.5,0.05)
y = np.arange(list(map(lambda t: f1(t),x)))

# 作图
plt.figure(facecolor='w')
plt.plot(x,y,'b-',linewidth='3')
plt.plot(GD_x,y,'r-',linewidth='3')
plt.title(u'函数 0.5*(x-0.25)^2$\n 学习率:(%.3f) 最优解:(%.3f, %.3f) 迭代次数:%.3d' %(alpha,x,f_current,iter_num))
plt.show()

报错内容:

img

  • 写回答

2条回答 默认 最新

  • threenewbee 2023-08-16 11:56
    关注

    lambda t: f1(t)
    这个直接写
    f1 就可以了
    而且不要 list
    因为arange需要的是元组,不是list

    评论

报告相同问题?

问题事件

  • 创建了问题 8月16日

悬赏问题

  • ¥200 基于同花顺supermind的量化策略脚本编辑
  • ¥20 Html备忘录页面制作
  • ¥15 黄永刚的晶体塑性子程序中输入的材料参数里的晶体取向参数是什么形式的?
  • ¥20 数学建模来解决我这个问题
  • ¥15 计算机网络ip分片偏移量计算头部是-20还是-40呀
  • ¥15 stc15f2k60s2单片机关于流水灯,时钟,定时器,矩阵键盘等方面的综合问题
  • ¥15 YOLOv8已有一个初步的检测模型,想利用这个模型对新的图片进行自动标注,生成labellmg可以识别的数据,再手动修改。如何操作?
  • ¥30 NIRfast软件使用指导
  • ¥20 matlab仿真问题,求功率谱密度
  • ¥15 求micropython modbus-RTU 从机的代码或库?