Python 错误:NameError: name is not defined [英] Python error: NameError: name is not defined

查看:605
本文介绍了Python 错误:NameError: name is not defined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import numpy as np
from scipy import optimize as opt
import time

def grad_d():
    weight = [0, 0]
    learnrate = 0.01
    tol = 1.e-5
    itmax = 1000

    for i in range(itmax):
        deltaweight = - learnrate * opt.rosen_der(weight)
        weight = weight + deltaweight
        if abs(deltaweight) < learnrate:
            break
    
    return weight, i
    
print('Weight: ', weight)
print('Iterations: ', i)

运行代码后,我收到错误消息:

After running the code, I receive error message:

文件c:/Users/Desfios 5/Desktop/Python/gradientdescent.py",第 19 行,在打印('重量:',重量)NameError: name 'weight' 未定义

"File "c:/Users/Desfios 5/Desktop/Python/gradientdescent.py", line 19, in print('Weight: ', weight) NameError: name 'weight' is not defined

我是 Python 新手,我不明白为什么它说变量weight"是显然在 grad_d() 下定义时未定义.

I am new to Python and I do not understand why it is saying that the variable "weight" is undefined when it clearly appears to be defined under grad_d().

推荐答案

你只是忘了调用你的函数试试:

You just forgot to call your function Try:

weight, i = grad_d()
print('Weight: ', weight)
print('Iterations: ', i)

这篇关于Python 错误:NameError: name is not defined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆