python(房价预测)

因为自身水平还未达到,有待进步,所以不会做这题。

以下为网络上找的代码。

# 计算赤峰面积和房价之间的关系

import numpy as np
import matplotlib.pyplot as plt
data = []
for i in range(300):
    area = np.random.uniform(60, 100)
    eps2 = np.random.uniform(60, 62)
    eps3 = np.random.uniform(200., 700.)
    
    price = eps2 * area + eps3 
    data.append([area, price])
data = np.array(data)  


area = data[:, 0]
price = data[:, 1]

plt.title("Area-Price") 
plt.scatter(area, price, s=10)  
plt.xlabel("area")  
plt.ylabel("price") 
plt.show()  
loss_list = []
def mse(b, w, data):  
    TotalError = 0  
    for i in range(0, len(data)):
        x = data[i, 0]
        y = data[i, 1]
        TotalError += (y - (w * x + b)) ** 2
    return TotalError / float(len(data))


def gradient_update(b, w, data, lr):
    b_gradient = 0
    w_gradient = 0
    size = float(len(data))
    for i in range(0, len(data)):
        x = data[i, 0]
        y = data[i, 1]
        b_gradient += (2 / size) * ((w * x + b) - y)
        w_gradient += (2 / size) * x * ((w * x + b) - y)
    b -= lr * b_gradient
    w -= lr * w_gradient
    return [b, w]



def gradient_descent(data, b, w, lr, num_iterations):
   for num in range(num_iterations):
        b, w = gradient_update(b, w, data, lr)
       
        loss = mse(b, w, data)
        loss_list.append(loss)
        print('iteration:[%s] | loss:[%s] | w:[%s] | b:[%s]' % (num, loss, w, b))
    return [b, w]


def main():
    lr = 0.00001
    initial_b = np.random.randn(1)
    initial_w = np.random.randn(1)
    num_iterations = 100  
    [b, w] = gradient_descent(data, initial_b, initial_w, lr, num_iterations)
    loss = mse(b, w, data)
    print('Final loss:[%s] | w:[%s] | b:[%s]' % (loss, w, b))
  
    plt.title("Loss Function")  
    plt.plot(np.arange(0, 100), loss_list)
    plt.xlabel('Interation')
    plt.ylabel('Loss Value')
    plt.show()

    y2 = w * area + b
    print(w * 100 + b)
    plt.title("Fit the line graph")  
    plt.scatter(area, price, label='Original Data', s=10)  
    plt.plot(area, y2, color='Red', label='Fitting Line', linewidth=2)
    plt.xlabel('m_j')
    plt.ylabel('j_g')
    plt.legend()
    plt.show()
main()

 

你可能感兴趣的:(python,numpy,开发语言)