如何使用Python的Matplotlib绘制梯度下降的3D图?

我在使用Python的Matplotlib绘制梯度下降的3D图时遇到了问题。gradient_descent函数中的注释代码是我尝试过的,但不起作用。我希望能得到任何解决方案,包括使用其他库的方案。下面的图表是我想要绘制的示例。

enter image description here

以下是代码:

import numpy as np
import matplotlib.pyplot as plt
def scatter_plot(x, y, x_title, y_title, g_title):
    plt.plot(x, y, 'bo')
    plt.xlabel(x_title)
    plt.ylabel(y_title)
    plt.title(g_title)
def plot_hypothesis(x, y, hyp, x_title, y_title, g_title):
    scatter_plot(x, y, x_title, y_title, g_title)
    plt.plot(x, hyp, '--')
    plt.show()
def gradient_descent(x, y, iterations, r):
    t0 = t1 = 0                                                                 # t0 = y-intercept, t1 = gradient
    m = len(x)                                                                  # Number of training examples
    h = 0                                                                       # Initialize 0 to the hypothesis
    cost = 0
    print("Learning Rate = ", r)
    print('Number of Iterations = ', iterations)
    for i in range(iterations):
        h = t0 + (t1 * x)                                                       # Set hypothesis
        cost = (1/(2 * m)) * sum([val**2 for val in (h - y)])                   # Calculate cost
        t0 = t0 - r * (1 / m) * sum(h - y)                                      # Partial derivative of t0 and update t0
        t1 = t1 - r * (1 / m) * sum((h - y) * x)                                # Partial derivative of t1 and update t1
        print("i={}, cost={}, t0={}, t1={}".format(i, cost, t0, t1))
    plot_hypothesis(x, y, h, 'year', 'life expectancy', 'Malaysian Males Life Expectancy At Birth')
    # fig = plt.figure()
    # ax = fig.add_subplot(111, projection='3d')
    # ax.plot_trisurf(cost, t1, t0, colot='None', alpha=0.5)
    # ax.set_xlabel('J(\u03B80,\u03B81)')
    # ax.set_ylabel('\u03B81')
    # ax.set_zlabel('\u03B80')
# main()
# x = year
x = np.array([1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015])
# y = life expectancy at birth
y = np.array([63.1, 63.5, 63.3, 63.8, 61.6, 62.6, 62.8, 63.2, 63.6, 64.3, 64.7, 65.3, 65.6, 65.8, 66.4, 66.9, 67.1, 67.1, 67.2, 67.7, 68.2, 68.5, 68.7, 68.8, 68.9, 69.2, 69.4, 69.6, 69.6, 69.5, 69.5, 69.7, 69.5, 69.7, 70, 70.6, 70.7, 70.8, 71.1, 71.4, 71.6, 71.6, 71.6, 71.7, 71.9, 72.1, 72.2, 72.4, 72.5, 72.5])
scatter_plot(x, y, 'year', 'life expectancy', 'Malaysian Males Life Expectancy At Birth')
plt.show()
gradient_descent(x, y, 100, 0.0000001)                                      

回答:

要创建一个3D表面图,一个非常基本的代码示例如下所示:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')   # Create the axes
# Data
X = np.linspace(-8, 8, 100)
Y = np.linspace(-4, 4, 100)
X, Y = np.meshgrid(X, Y)
Z = X**2 + Y**2
# Plot the 3d surface
surface = ax.plot_surface(X, Y, Z,
                          cmap=cm.coolwarm,
                          rstride = 2,
                          cstride = 2)
# Set some labels
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
plt.show()

结果如下:

然而,要创建你想要的梯度下降的3D表面图,你需要重新考虑你需要绘制哪些数据。例如,你需要一系列所有的thetascosts。根据plot_surface的工作原理,尝试弄清楚你需要哪些数据,并相应地修改你的gradient_descent函数。同时,查看这个实现也是有帮助的。

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中创建了一个多类分类项目。该项目可以对…

发表回复

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