社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python函数找不到全局变量

Ben Leonard • 3 年前 • 1275 次点击  

我正在为Python中的线性回归程序创建一个计算b1的程序。

当试图给b1全局变量赋值时,IDE找不到它。你可以在函数的最后一行找到变量赋值。

x_data = [4, 8, 6, 3, 4, 6, 2, 1, 3]
y_data = [2, 4, 7, 3, 4, 8, 3, 2, 5]
b1 = 0

def b0_b1_calc():
    x_sum = 0
    y_sum = 0
    for i in x_data:
        x_sum += x_data[i]
        y_sum += y_data[i]
    x_mean = round(1, x_sum / len(x_data))
    y_mean = round(1, y_sum / len(y_data))
    x_list = []
    y_list = []
    for i in x_data:
        x_list.append(i - x_mean)
        y_list.append(i - y_mean)
    x_minus_x_squared = []
    for i in x_list:
        x_minus_x_squared.append((x_list[i] - x_mean) ** 2)
    x_sum = sum(x_minus_x_squared)
    x_y = []
    for i in x_data:
        x_y.append(y_list * x_list)
    x_y = sum(x_y)
    b1 = x_y / x_sum
    
print(str(b1))




    
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130817
 
1275 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Kumar Arnav
Reply   •   1 楼
Kumar Arnav    3 年前

请申报 b1 global 在以下功能中:

    def b0_b1_calc():
       global b1
       # remaining code in the function
Freddy Mcloughlan
Reply   •   2 楼
Freddy Mcloughlan    3 年前

你必须使用 global 访问全局变量。代码中还有一些错误,我已经修复并注释了这些错误:

def b0_b1_calc():
    # Use global to access global variables
    global b1

    # sum() summates a list
    x_sum = sum(x_data)
    y_sum = sum(y_data)

    # This was the wrong way around
    x_mean = round(x_sum / len(x_data))
    y_mean = round(y_sum / len(y_data))

    x_list = []  # could also be [i - x_mean for i in x_data]
    y_list = []  # could also be [i - y_mean for i in x_data]

    for i in x_data:
        x_list.append(i - x_mean)
        y_list.append(i - y_mean)

    # could also be [(x_list[i] - x_mean) ** 2 for i in x_list]
    x_minus_x_squared = []

    for i in x_list:
        x_minus_x_squared.append((x_list[i] - x_mean) ** 2)

    x_sum = sum(x_minus_x_squared)
    x_y = []

    for i in x_data:
        # could be simplified to [np.array(y_list) * np.array(x_list) for i in x_data]
        # use np.array for vectorial array multiplication
        x_y.append(np.array(y_list) * np.array(x_list))
    
    x_y = sum(x_y)
    b1 = x_y / x_sum


b0_b1_calc()

绕开环球旅行的首选方式是打电话 return :

def b0_b1_calc():
    # ... code here
    return b1

b1 = b0_b1_calc()