提问人:The Myth 提问时间:3/6/2023 最后编辑:The Myth 更新时间:3/8/2023 访问量:79
根据其他变量为一个变量生成方程
Generate equation for one variable in terms of others
问:
我有一个特定的数据集,其中有 3 个不同的函数和 3 个不同的变量:
x = 1
strLen_x = int(3**x + 0.25*(-3*(-1)**x + 3**x + 6)) # Function 1
y = 2
strLen_y = 2*y # Function 2
z = 3
strLen_z = 3*(z + 1 + (z//4)) # Function 3
# Expecting Function 4 in terms of 1, 2, and 3
最终输出,即......变量只不过是依赖于 3 个不同变量的变量。
我试图想出一个通用方程,其中是所有 3 个变量 ()。strLen_
x, y, and z
strLen_xyz
x, y, z
下面是具有不同值的输出的表。
注意:所有变量都是正整数。x, y, z
y > 1
这里,是要获得的最终值。Output
答:
1赞
duffymo
3/7/2023
#1
这是我的完整答案。此代码使用 Scikit Learn 对数据执行多变量二阶多项式回归:
# see https://stackoverflow.com/questions/75650950/generate-equation-for-one-variable-in-terms-of-others
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
def mse(y_test, predictions):
return np.mean((y_test-predictions)**2)
if __name__ == "__main__":
df = pd.read_csv('../resources/strlen.csv')
cols = df.select_dtypes(np.number).columns
X = df[['x', 'y', 'z']].to_numpy()
y = df[['len']].to_numpy()
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
y_scaled = scaler.fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234)
reg = linear_model.LinearRegression()
reg.fit(X_train, y_train)
predictions = reg.predict(X_test)
err = mse(y_test, predictions)
print("Error : ", err)
print("Intercept : ", reg.intercept_ )
print("Coefficients: ", reg.coef_)
y_pred_line = reg.predict(X)
cmap = plt.get_cmap('viridis')
fig = plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x='x', y='len', hue='y', style='z')
sns.lineplot(data=df, x='x', y='len')
x_line = np.linspace(df.iloc[:, 0:3].min(axis=0), df.iloc[:, 0:3].max(axis=0), num=11)
y_line = np.array(reg.intercept_[0] + np.matrix(x_line) * np.matrix(reg.coef_.transpose()))
print('x_line: ', x_line, ' shape: ', x_line.shape)
print('y_line: ', y_line, ' shape: ', y_line.shape)
m1 = plt.plot(x_line[:, 0], y_line, color='red')
plt.show()
这是我用你的数据创建的.csv:
x,y,z,len
12,6,6,12
12,4,12,16
36,4,6,10
36,4,24,60
36,4,6,10
36,8,9,160
102,6,6,102
306,4,9,80
306,4,24,240
306,8,24,7680
306,8,27,8960
306,10,21,19535
306,10,27,27345
912,10,21,97660
912,10,24,117190
912,10,36,175785
在代码中修复文件的路径并运行它。
这是数据图。红线是线性拟合结果:
我使用了一个完整的二阶多项式:.y = a0 + a1*x + a2*y + a3*z + a4*x^2 + a5*x*y + a6*x*z + a7*y^2 + a8*y*z + a9*z*z
您可以通过打印来查看系数。reg.coef_
评论
0赞
Kelly Bundy
3/7/2023
你能展示一下方程式吗?
0赞
duffymo
3/7/2023
它的系数是线性的。看到y_line了吗?
0赞
Kelly Bundy
3/7/2023
我在代码中看到了它,但我没有看到结果。
0赞
duffymo
3/7/2023
我已经编辑了代码。你会看到一条红线,可以清楚地说明这一点。
评论
strLen = strLen_x + strLen_y + strLen_z
import sympy as sym; x, y, z = sym.symbols('x y z'); strLen_x = sym.floor(3**x + 0.25*(-3*(-1)**x + 3**x + 6)); strLen_y = 2*y; strLen_z = 3*(z + 1 + (z//4))
strLen_x