TypeError:只有长度为1的数组才能转换为Python标量
我有以下Python脚本:TypeError:只有长度为1的数组才能转换为Python标量,python,numpy,Python,Numpy,我有以下Python脚本: import math import numpy as np scores = [3.0, 1.0, 0.2] y = [0,0,0] i = 0 j = 0 k = 0 sum = 0 def myFunc(x): global sum global i global j if not y: for s in scores: y[i] = 0.5 * scores[i] + 0.2
import math
import numpy as np
scores = [3.0, 1.0, 0.2]
y = [0,0,0]
i = 0
j = 0
k = 0
sum = 0
def myFunc(x):
global sum
global i
global j
if not y:
for s in scores:
y[i] = 0.5 * scores[i] + 0.2
i = i+1
if sum == 0:
for s2 in scores:
sum = sum + math.exp(y[j])
j = j+1
print sum
return math.exp(x)/sum
for s3 in scores:
print(myFunc(scores[k]))
k = k+1
我这里有两个问题:
- 我没有得到
的预期输出,这使得总结果是错误的sum
- 当我运行脚本时,我得到以下输出:
Traceback (most recent call last): File "myFunc.py", line 40, in <module> plt.plot(x, myFunc(scores).T, linewidth=2) File "myFunc.py", line 30, in myFunc return math.exp(x)/sum TypeError: only length-1 arrays can be converted to Python scalars
回溯(最近一次呼叫最后一次): 文件“myFunc.py”,第40行,在 plt.plot(x,myFunc(分数).T,线宽=2) 文件“myFunc.py”,第30行,在myFunc中 返回数学表达式(x)/sum TypeError:只有长度为1的数组才能转换为Python标量
谢谢。看起来你想要这样的东西:
import numpy as np
def func(scores):
y = 0.5 * scores + 0.2
return scores / np.sum(np.exp(y))
scores = np.array([3.0, 1.0, 0.2])
for res in func(scores):
print(res)
输出:
0.339460254992
0.113153418331
0.0226306836661
现在您还可以绘制它:
from matplotlib import pyplot as plt
plt.plot(func(scores).T, linewidth=2)
您有三个for循环。是什么导致了你的问题?带有
plt.plot
的第40行不存在。请把这个削减到最低限度。这是一个巨大的非蟒蛇,但我很难弄清楚你首先想要做什么。