我试图通过使用其他列表作为函数的参数来制作列表。然而,我似乎不能得到正确的语法。
这是我的代码:
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)
这返回
[3, 6] [5, 1] [2, 5] [7, 8]
[5, 25]
使用zip
将三个列表压缩为一个3元组列表,解压缩该3元组,然后将每个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))
为t
与thetas
的点积。
def dotp(x, y):
return sum(map(mul, x, y))
f1 = [dotp(t, thetas) for t in zip(*trains)]
我建议你试试这个简单的代码:
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]