我想使用列表作为参数从函数的结果中创建一个列表

I want to make a list from the outcome of a function using lists as arguments

我正在尝试通过使用其他列表作为函数的参数来创建列表。但是,我似乎无法获得正确的语法。
这是我的代码:

f1 = theta0 + theta1*(X1_train) + theta2*(X2_train)+theta3*(X3_train)

预期的结果将是 X1_train、X2_train 和 X3_train 的相同长度列表(对于这 3 个是相同的)。

我希望得到列表 X1_train、X2_train 和 X3_train 中每个元素的结果列表作为函数的参数。例如,如果我的列表是

X1_train = [0, 1]
X2_train = [1, 2]
X3_train = [0, 2]

我希望得到像

这样的数字列表
f1 = [theta0 + theta2, theta0 + theta1 + theta2 + 2*theta3]

thethas 是随机数。

此列表是我转换为列表的数据框的列,因此我可以执行此功能。

希望对您有所帮助:

import random

X1_train = [0,1]
X2_train = [1,2]
X3_train = [0,1]

amnt = 2

theta0 = random.sample(range(1, 10), amnt)
theta1 = random.sample(range(1, 10), amnt)
theta2 = random.sample(range(1, 10), amnt)
theta3 = random.sample(range(1, 10), amnt)

EndValues = []
for i in range(0, len(X1_train)):

f1 = theta0[i] + theta1[i] * X1_train[i] + theta2[i] * X2_train[i] + theta3[i] * X3_train[i]
EndValues.append(f1)

print(EndValues)

这个returns

[3, 6] [5, 1] [2, 5] [7, 8]
[5, 25]

我建议你试试这个简单的代码:

def f(X: tuple, theta: tuple):
   if not isinstance(X, tuple):
      raise TypeError('X must be a tuple')
   if not isinstance(theta, tuple):
      raise TypeError('theta must be a tuple')
   if not X.__len__() == theta.__len__():
      raise ValueError('length of tuples is not equal')
   return sum([np.array(x_)*t_ for x_, t_ in zip(X, theta)])

请注意,如果 X 或 Theta 不是相同长度的元组,则会引发错误。

示例:(应该按原样工作

import numpy as np
X1_train = [0, 1]
X2_train = [1, 2]
X3_train = [0, 2]

theta_1 = 1
theta_2 = 1
theta_3 = 3
print(f(
    (X1_train, X2_train, X3_train),
    (theta_1, theta_2, theta_3)
    ))
>>> [1 9]

使用zip将三个列表压缩成一个三元组列表,解压缩三元组,然后将每个theta值乘以其对应的元素,然后对结果求和。

f1 = [theta0 + theta1*x1 + theta2*x2 + theta3*x3
      for x1, x2, x3 in zip(X1_train, X2_train, X3_train)]

如果你认为 theta0 是 1 的倍数,你可以将其概括为

from itertools import repeat


f1 = [theta0*x0 + theta1*x1 + theta2*x2 + theta3*x3
      for x0, x1, x2, x3 in zip(repeat(1), X1_train, X2_train, X3_train)]

你可以减少到

from operator import mul
thetas = [theta0, theta1, theta2, theta3]
trains = [repeat(1), X1_train, X2_train, X3_train]
f1 = [sum(map(mul, t, thetas)) for t in zip(*trains)]

sum(map(mul, t, thetas)) 只是 tthetas 的点积。

def dotp(x, y):
    return sum(map(mul, x, y))

f1 = [dotp(t, thetas) for t in zip(*trains)]