为新数据集创建梯度下降模型时出错[已关闭]

问题描述 投票:0回答:1
import pandas as pd 

file = pd.read_excel('slr06.xlsx')
# Data 
x = pd.DataFrame(file, columns=['X'])
y = pd.DataFrame(file, columns=['Y'])
# Parameters 
w = 0.0
b = 0.0
# HyperParameters 
learning_rate = 0.01

# Creating Gradient Descent 

def descend(x, y, w, b, learning_rate):
    dl_dw = 0.0
    dl_db = 0.0
    n = x.shape[0]
    # loss = (y-yhat)**2
    for xi, yi in zip(x, y):
        dl_dw = -2*xi*(yi-(w*xi+b))
        dl_db = -2*(yi-(w*xi+b))
    # Make an Update
    w = w - learning_rate*(1/n)*dl_dw
    b = b - learning_rate*(1/n)*dl_db
    
    return w, b
# Iteratively make updates 
for epoch in range(500):
    w, b = descend(x, y, w, b, learning_rate)
    yhat = w * x + b
    loss = np.divide(np.sum((y - yhat)**2, axis=0), x.shape[0])
    print(f"{epoch} loss is {loss} parameters w: {w} | b:{b}")

我是机器学习新手,我正在使用数据集进行练习,但出现错误

This is the picture of a dataset -

This is the picture of error -

我正在创建一个梯度下降模型,我之前已经使用不同的数据集练习过该模型。我尝试使用随机数据来练习并更好地理解梯度下降

python machine-learning jupyter
1个回答
0
投票

这个不明确的错误来自错误的数据类型,即由于像

[1,2] * 1.0 or "hello" * 3

这样的乘法

您的错误来自与此类似的错误迭代方法:

>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
>>> for x in df:
...     print(x)
A
B

您的

xi, yi
变量是字符串,当与浮点数相乘时会导致错误。


您可以通过多种方式更改代码。然而,最有效的方法是:

# Do not duplicate memory, and use a Series instead of a data frame
x = file.X
y = file.Y

现在 for 循环部分不再抛出错误。 此外,如果您进行完整的批量梯度下降,您可以使用矢量化而不需要 for 循环。


PS:要记住的事情:迭代数据框通常是一个坏主意,因为有更有效的方法。

© www.soinside.com 2019 - 2024. All rights reserved.