我想用一些动态输入创建一个线性方程
y = θ0*x0 + θ1*x1
或
y = θ0*x0 + θ1*x1 + θ2*x2 + θ3*x3 + θ4*x4
为此我有 x0,x1,x2......xn 的字典 和 θ0,θ1,θ2......θn 的数组
我是Python新手,所以我尝试了这个函数,但我卡住了
所以我的问题是如何编写一个函数来获取 x_values 和 theta_values 作为参数并给出 y_values 作为输出
X = pd.DataFrame({'x0': np.ones(6), 'x1': np.linspace(0, 5, 6)})
θ = np.matrix('0 1')
def line_func(features, parameters):
result = []
for feat, param in zip(features.iteritems(), parameters):
for i in feat:
result.append(i*param)
return result
line_func(X,θ)
最佳答案
如果您想将 theta 与一系列特征相乘,那么从技术上讲,您可以将矩阵(特征)与向量(theta)相乘。
您可以按如下方式执行此操作:
import numpy as np
x_array= x.values
theta= np.array([theta_0, theta_1])
x_array.dot(theta)
只需按照 x 中列的排序方式对 theta 向量进行排序即可。但请注意,这给出了所有 is 的 theta_i*x_i 的乘积的行总和。如果不想rowise求和,只需要写x_array * theta即可。
如果您还想使用 pandas(我不推荐)进行乘法运算,并希望获得包含列值和相应 theta 的乘积的数据框,您可以按如下方式执行此操作:
# define the theta-x mapping (theta-value per column name in x)
thetas={'x1': 1, 'x2': 3}
# create an empty result dataframe with the index of x
df_result= pd.DataFrame(index=x.index)
# assign the calculated columns in a loop
for col_name, col_series in x.iteritems():
df_result[col_name]= col_series*thetas[col_name]
df_result
这会导致:
x1 x2
0 1 6
1 -1 3
关于python - 如何同时使用字典和数组的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57499216/