关于梯度下降成本随Epoch变化的绘图问题

我正在尝试绘制梯度下降的成本列表(cost_list)随Epoch的变化图,但当我尝试这样做时,我在基本的Python函数结构上遇到了困难。我附上了我正在尝试的代码结构。

def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.T
    cost_list=[]
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        cost = np.sum(loss ** 2) / (2 * m)
        cost_list.append(cost)
        print("Iteration %d | Cost: %f" % (i, cost))
        # 每个样本的平均梯度
        gradient = np.dot(xTrans, loss) / m
        # 更新
        theta = theta - alpha * gradient
        #a = plt.plot(i,theta)
    return theta,cost_list

我正在尝试在每一步返回“cost_list”,创建一个成本列表,然后使用下面的代码行进行绘图。

theta,cost_list=gradientDescent(x,y,bias,0.000001,len(my dataframe),100)
plt.plot(list(range(numIterations)), cost_list, '-r')

但是它提示我错误,说numIterations未定义。代码应该做哪些可能的修改?


回答:

我使用样本数据尝试了你的代码;

df = pd.DataFrame(np.random.randint(1,50, size=(50,2)), columns=list('AB'))
x=df.A
y=df.B
bias = np.random.randn(50,1)
numIterations = 100
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(df),numIterations)
plt.plot(list(range(numIterations)), cost_list, '-r')

enter image description here

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注