1

我正在尝试创建三个 [1, m] numpy 矩阵的等高线图。当我尝试绘制时:

plt.contour(reg.theta[0,:], reg.theta[1,:], reg.J[0,:])

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我认为这与以下事实有关

In[167]: shape(reg.theta[0,:])

Out[167]: (1, 15000)

轮廓想要一些类似的东西(15000,)

我试图创建一个类似于我在 matlab 中使用的网格网格

X , Y = meshgrid(reg.theta[0,:], reg.theta[1,:]

ValueError: total size of new array must be unchanged[1,:])

但是,我不知道如何解释这一点。

请指教stackoverflow!

这是我在 Python 2.7 上测试的完整代码

from numpy import *
import matplotlib.pyplot as plt
class LinearRegression: 

    def __init__(self, data):

        self.data_loc = data
        self.max_it = 15000
        self.theta = matrix(ones((2, self.max_it)))
        self.alpha = .01
        self.J = matrix(zeros((1, self.max_it)))


    def importData(self):

        Data = loadtxt(self.data_loc, delimiter = ',')
        rawData = matrix(Data)
        x = rawData[:,0]
        y = rawData[:,1]
        [m,n] = shape(x)
        x_0 = matrix(ones((m,1)))
        x = concatenate((x_0, x), axis = 1)

        return x, y, m, n

    def center(self, x):

        x = x / mean(x)

        return x 

    def scale(self, x):

        x = x/ std(x)

        return x 

    def funct(self, m, b):

        return lambda x: m*x + b 


    def cost(self, x, y, m, mx, b):

        f = self.funct(mx, b)
        err = power( (f(x) - y), 2).sum()
        err = err / (2*len(x))

        return err

    def gradientDesc(self, x, y, m):

        for i in range(0, self.max_it -1):

            error = (1.0/m) * transpose(x) * ((x * self.theta[:,i]) - y ) 
            delta = self.theta[:,i] - self.alpha*error

            self.J[0,i] = (self.cost( x, y, m, self.theta[1,i], self.theta[0,i]))

            self.theta[:, i+1] = delta

        print('Calculation Complete')
        return self.theta, error


reg = LinearRegression('/users/michael/documents/machine_learning/ex1/ex1data1.txt')
x, y, m ,n = reg.importData()
theta, error = reg.gradientDesc(x,y,m)
print (reg.theta[:,reg.max_it -1])
XX = linspace(0,m,m)
J = reg.theta[0,reg.max_it-1] + reg.theta[1, reg.max_it-1] * XX 
plt.plot(XX, J)
plt.scatter(x[:,1],y)`
4

0 回答 0