使用梯度下降的线性回归
参考:Linear Regression Using Gradient Descent in 10 Lines of Code
数据集:
房价卧室数
编码环境:Google合作实验室
代码:
import numpy as np
import pandas as pd
import io
from google.colab import files
uploaded = files.upload()
df = pd.read_csv(io.BytesIO(uploaded['datasets_46927_85203_data.csv']))
house_price=df.price
No_of_bedrooms=df.bedrooms
# Mean of house_price and No_of_bedrooms
mean_x= np.mean(house_price)
mean_y=np.mean(No_of_bedrooms)
#Total number of datapoints
n=len(house_price)
numerator = 0;
denominator = 0;
for i in range (n):
numerator += (house_price[i] - mean_x) * (No_of_bedrooms[i] - mean_y)
denominator += (house_price[i] - mean_x) ** 2
slope= numerator / denominator
constant = mean_y - (slope*mean_x)
def linear_regression(house_price[], y, m_current=slope, b_current=constant, epochs=1000,
learning_rate=0.0001):
N = float(len(No_of_bedrooms))
for i in range(epochs):
y_current = (m_current * house_price[i]) + b_current
cost = sum([data**2 for data in (No_of_bedrooms[i]-y_current)]) / N
m_gradient = -(2/N) * sum(house_price[i] * (No_of_bedrooms[i] - y_current))
b_gradient = -(2/N) * sum(No_of_bedrooms[i] - y_current)
m_current = m_current - (learning_rate * m_gradient)
b_current = b_current - (learning_rate * b_gradient)
return m_current, b_current, cost
错误:def linear_regression(house_price[], y, m_current=slope, b_current=constant, epochs=1000, learning_rate=0.0001):
Error Statement: File "<ipython-input-6-864b867cbc7a>", line 31
def linear_regression(house_price[], y, m_current=slope, b_current=constant, epochs=1000, learning_rate=0.0001):
^
SyntaxError: invalid syntax
我不知道如何消除此错误。
此post与我的查询无关。
如果有人帮助我,那将很棒。谢谢。