我正在尝试使用简单的线性回归来预测某个项目的成本。我使用商品的成本作为输入数据。
代码似乎有效,但我不知何故无法理解应用线性回归时如何使用 X 和 Y。我使用 X 作为项目成本,Y 作为标签(使用 X 的移位数据创建一个新行)
df = df[['Item Price']]
forecast_col = 'Item Price'
forecast_out = int(math.ceil(0.0000005 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)
X = df[['Item Price']]
X = preprocessing.scale(X)
X_lately = X[forecast_out:]
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
forecast_set = clf.predict(X)
X和Y变量如何用于求解Y = a + bX的线性回归方程
最佳答案
您的线路:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
将 X 和 y 分别分成两个样本:包含 80% 数据的训练和使用其他 20% 数据的测试。然后一行:
clf = LinearRegression(n_jobs=-1)
创建线性模型。最后一行:
clf.fit(X_train, y_train)
线性模型使用 X_train 和 Y_train 中的所有 (x,y) 来计算最佳线性回归器。
在更数学的方法中,该算法使用 X_train 和 Y_train 中包含的所有 (x, y) 来查找使方程 E 最小化的 a 和 b:
E = SUM(y_i - a*x_i - b)
通过查找E的导数和E的二阶导数等于0的位置来找到a和b值
关于python - 这些 X 和 Y 变量如何在线性回归中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363130/