如何为matplotlib表面图创建二维Z值?

我正在尝试创建线性回归误差函数的表面图。我这样做:

class LinearRegression:
    def __init__(self):
        self.data = pd.read_csv("data.csv")
    def computeCost(self):
        j = 0.5 * (
            (self.data.hypothesis - self.data.y)**2).sum() / self.data.y.size
        return j
    def regress(self, theta0, theta1):
        self.data["hypothesis"] = theta1 * self.data.x + theta0
    def plotCostFunction3D(self):
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        theta0_vals = np.linspace(-100, 100, 200)
        theta1_vals = np.linspace(-100, 100, 200)
        costs = []
        for theta0 in theta0_vals:
            for theta1 in theta1_vals:
                self.regress(theta0, theta1)
                costs.append(self.computeCost())
        ax.plot_surface(
            theta0_vals,
            theta1_vals,
            np.array(costs),
        )
if __name__ == "__main__":
    regression = LinearRegression()
    regression.plotCostFunction3D()
    plt.show()

我遇到了以下错误:

ValueError: Argument Z must be 2-dimensional.

我知道我需要对theta0_valstheta1_vals使用np.meshgrid,但我不确定如何从这些结果中计算成本。我该如何处理这个问题呢?


回答:

错误是由方法调用ax.plot_surface(theta0_vals, theta1_vals, np.array(costs))引起的,因为Axes3D.plot_surface(X, Y, Z)期望其参数是二维数组。

正如你所指出的,应该使用np.meshgrid()来计算由theta0_valstheta1_vals跨越的网格。对于Z,你已经使用嵌套的for循环计算了网格上每个点的成本,所以你只需要将一维的costs列表转换成对应于X-Y网格的二维数组。这可以通过np.reshape()来完成。

    def plotCostFunction3D(self):
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        theta0_vals = np.linspace(-100, 100, 200)
        theta1_vals = np.linspace(-100, 100, 200)
        costs = []
        for theta0 in theta0_vals:
            for theta1 in theta1_vals:
                self.regress(theta0, theta1)
                costs.append(self.computeCost())
        X, Y = np.meshgrid(theta0_vals, theta1_vals)
        Z = np.reshape(costs, (200, 200))
        ax.plot_surface(X, Y, Z)

为了获得更好的性能,最好避免使用嵌套的for循环。你可以将X-Y网格点存储在一个数据框中,然后使用df.apply()计算Z列。

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

发表回复

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