【发布时间】:2020-02-18 05:32:23
【问题描述】:
在此函数中,exs 被假定为浮点列表的列表。它代表了我所有训练示例的列表,每个示例都是一个浮点列表(长度num_vars),代表感知器输入。 target 被假定为浮点数列表(长度 num_vars),表示目标函数的系数。
def gradDesc(exs, target, num_vars, n=0.5, its=256):
import random
weights = []
# Create and initialize delWeights to 0. Make its size num_vars.
delWeights = [0.0]*num_vars
# Initializes the weights to a real number in [-1,1]. Also makes weights
# contain num_vars entries.
for i in range(num_vars):
weights.append(random.uniform(-1,1))
# To make the printouts look nicer
print("Iteration\tError")
print("---------\t-----")
for i in range(its):
# Reset delWeights to 0
for j in range(num_vars):
delWeights[j] = 0
for e in exs:
# Plug e into the current hypothesis and get the output.
output = test_hypo(weights, e, num_vars)
print("delWeights: ", delWeights)
for dw in delWeights:
print("type(dw): ", type(dw))
delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]
for w in weights:
weights[w] = weights[w] + delWeights[dw]
# Print out the error every tenth iteration
if i % 10 == 0:
print(i + "\t" + train_err(exs, target, weights, num_vars))
# Print out the final hypothesis
print(i + "\t" + train_err(exs, target, weights, num_vars))
return weights
问题是,当我尝试在给定(有限)测试输入的情况下运行它时
trainers =
[[1, 2.7902232015508766, -4.624194135789617],
[1, -7.964359679418456, 2.1940274082288624],
[1, 8.445941538761794, -8.86567924774781],
... other sub-lists following this same format ...]
和
target = [-2, 1, 2]
我得到了这个奇怪的输出:
gradDesc(trainers, target, num_vars)
Iteration Error
--------- -----
delWeights: [0, 0, 0]
type(dw): <class 'int'>
type(dw): <class 'int'>
type(dw): <class 'int'>
delWeights: [0.0, 0, 0]
type(dw): <class 'float'>
Traceback (most recent call last):
File "<ipython-input-19-97298b385113>", line 1, in <module>
gradDesc(trainers, target, num_vars)
File "C:/Users/Me/.spyder-py3/Machine Learning/gradDesc.py", line 107, in gradDesc
delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]
TypeError: list indices must be integers or slices, not float
所以我的问题是:为什么 dw 的类型在通过 for e in exs 循环的第二次迭代中从 int 变为 float?
【问题讨论】:
-
你为什么在
for dw in delweights:循环之外使用dw变量? -
为什么要先将
delWeights初始化为0.0的列表,然后在for i in range(its):循环内用0替换它?为什么不delWeights = [0]*num_vars?
标签: python loops types nested iterator