Esempio n. 1
0
def plot(X, y, theta):
    # Valores de theta0 e theta1 informados no enunciado do trabalho
    theta0 = np.arange(-10, 10, 0.01)
    theta1 = np.arange(-1, 4, 0.01)

    # Inicia os valores de J com zeros
    J = np.zeros((len(theta0), len(theta1)))

    # Preenche os valores sucessivos de J
    for i in range(len(theta0)):
        for j in range(len(theta1)):
            t = [[theta0[i]], [theta1[j]]]
            J[i,j] = custo_reglin_uni(X, y, t)

    # Transpoe J devido as funcoes contour/meshgrid
    J = np.transpose(J)

    # Plota a funcao de custo utilizando levels como logspace. Range -1 ~ 4 devido ao
    # range de theta1 e 20 pois o theta0 tem 20 valores (-10 ate 10)
    fig = plt.figure()
    fig, ax = plt.subplots()
    ax.contour(theta0, theta1, J, levels=np.logspace(-1, 4, 20), color='blue')
    ax.plot(theta[0,0], theta[1,0], 'rx')
    plt.xlabel('theta0')
    plt.ylabel('theta1')
    plt.show()

    filename = 'target/plot1.3.1.png'
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))

    plt.savefig(filename)

    return J
Esempio n. 2
0
def gd_reglin_uni(X, y, alpha, epochs, theta = np.array([0,0], ndmin = 2).T):

    m = len(y)

    cost = np.zeros(epochs)

    for i in range(epochs):
    	h = X.dot(theta)
    	loss = h - y
    	gradient = X.T.dot(loss) / m
    	theta = theta - (alpha * gradient)
    	cost[i] = custo_reglin_uni(X, y, theta = theta)

    return cost[-1], theta
Esempio n. 3
0
def gd_reglin_uni(X, y, alpha, epochs, theta=np.array([0, 0], ndmin=2).T):

    #tamanho do conjunto de treinamento
    m = len(y)

    #calcula o custo para cada valor (epochs) a ser adotado por theta
    cost = np.zeros(epochs)
    #range de saltos a serem usados em theta
    for i in range(epochs):
        #calcula o valor da hipótese para a combinação de x e theta
        h = X.dot(theta)
        #calcula a diferença entre o valor da hipótese gerada e o y correspondente
        loss = h - y
        #calcula o gradiente da função, ou seja, se o valor de theta está maior ou menor que o desejado
        gradient = X.T.dot(loss) / m
        #calcula novo valor para theta
        theta = theta - (alpha * gradient)
        #calcula novo custo da função
        cost[i] = custo_reglin_uni(X, y, theta=theta)

    return cost[-1], theta
Esempio n. 4
0
dataset = pd.read_csv('ex1data1.txt', header=None)

x = dataset.iloc[:, 0:-1].values
y = dataset.iloc[:, -1:].values

plt.scatter(x, y, color='red', marker='x')
plt.title('Populaçãoo da cidade x Lucro da filial')
plt.xlabel('População da cidade (10k)')
plt.ylabel('Lucro (10k)')
plt.show()

# Incluir o valor de 1 em x, pois theta0 = 1
x = np.c_[np.ones((x.shape[0], 1)), x]

# Conforme solicitado no enunciado para iniciar todos os parâmetros com zero
print(custo_reglin_uni(x, y, theta=np.array([0, 0], ndmin=2).T))

# Conforme solicitação no texto do trabalho inicie o valor da taxa de aprendizagem com 0.01
cost_final, theta = gd_reglin_uni(x, y, 0.01, 5000)
print(cost_final)

x = dataset.iloc[:, 0:-1].values
t = np.arange(0, 25, 1)
plt.scatter(x, y, color='red', marker='x', label='Training Data')
plt.plot(t, theta[0] + (theta[1] * t), color='blue', label='Linear Regression')
plt.axis([4, 25, -5, 25])
plt.title('População da cidade x Lucro da filial')
plt.xlabel('População da cidade (10k)')
plt.ylabel('Lucro (10k)')
plt.legend()
plt.show()