首页 > 解决方案 > 如何同时使用带有字典和数组的for循环

问题描述

我想用一些动态输入做一个线性方程,就像它可以

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,θ)

标签: pythonpandasnumpy

解决方案


如果您想将您的 theta 与特征列表相乘,那么从技术上讲,您可以将矩阵(特征)与向量(theta)相乘。

您可以按如下方式执行此操作:

import numpy as np

x_array= x.values
theta= np.array([theta_0, theta_1])
x_array.dot(theta)

只需按照列在 x 中的排序方式对您的 theta 向量进行排序。但请注意,这给出了 theta_i*x_i 的乘积的逐行总和。如果你不希望它被汇总,你只需要写 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

推荐阅读