【问题标题】:Represent Linear Regression features in Gradient Descent numerically以数值方式表示梯度下降中的线性回归特征
【发布时间】:2016-02-11 09:39:03
【问题描述】:

以下 Python 代码可以很好地找到梯度下降:

def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y 
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        gradient = np.dot(xTrans, loss) / m 
        theta = theta - alpha * gradient
    return theta

这里,x = m*n(m = 样本数据数量,n = 总特征)特征矩阵。

但是,如果我的特征是“2”电影的非数字特征(例如导演和类型),那么我的特征矩阵可能如下所示:

['Peter Jackson', 'Action'
 Sergio Leone', 'Comedy']

在这种情况下,如何将这些特征映射到数值并应用梯度下降?

【问题讨论】:

    标签: machine-learning linear-regression gradient-descent


    【解决方案1】:

    您可以将您的特征映射到您选择的数值,然后以通常的方式应用梯度下降。

    在 python 中,你可以使用 panda 轻松做到这一点:

    import pandas as pd
    df = pd.DataFrame(X, ['director', 'genre'])
    df.director = df.director.map({'Peter Jackson': 0, 'Sergio Leone': 1})
    df.genre = df.genre.map({'Action': 0, 'Comedy': 1})
    

    如您所见,这种方式可能会变得相当复杂,最好编写一段代码来动态完成。

    【讨论】:

    • 您举了一个非常简单的例子,当您有 3 个可能的分类变量值时,您不能(不应该)将它们编码为“0”、“1”、“2”
    • @lejlot 能否为此类问题提出正确的方法?
    • Mathias 方法很好,只是他的示例可能会误导具有多个值的情况。典型的映射是“一个热编码”,因此对于具有 M 个可能值的特征,您添加到表示 M 个新维度,因此类型 e ['action', 'comedy', 'drama'] 现在是 3 个新维度,如果您的电影是戏剧则为 001,如果是喜剧则为 010,依此类推。
    • 我同意这是一个非常简单的解决方案,并不适合更高的维度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2017-06-20
    • 2019-10-09
    • 1970-01-01
    • 2016-10-22
    • 2017-01-02
    相关资源
    最近更新 更多