小编ale*_*der的帖子

为什么TF Keras推理比Numpy运算慢?

我正在使用Keras和Tensorflow实施强化学习模型。我必须在单个输入上频繁调用model.predict()。

在对简单的预训练模型进行推理测试时,我注意到使用Keras的model.predict比仅对存储的权重使用Numpy慢。为什么这么慢,我如何加速呢?对于复杂模型,使用纯Numpy不可行。

import timeit
import numpy as np
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense

w = np.array([[-1., 1., 0., 0.], [0., 0., -1., 1.]]).T
b = np.array([ 15., -15., -21., 21.])

model = Sequential()
model.add(Dense(4, input_dim=2, activation='linear'))
model.layers[0].set_weights([w.T, b])
model.compile(loss='mse', optimizer='adam')

state = np.array([-23.5, 17.8])

def predict_very_slow():
    return model.predict(state[np.newaxis])[0]

def predict_slow():
    ws = model.layers[0].get_weights()
    return np.matmul(ws[0].T, state) + ws[1]

def predict_fast():
    return np.matmul(w, state) + b

print(
    timeit.timeit(predict_very_slow, number=10000),
    timeit.timeit(predict_slow, number=10000),
    timeit.timeit(predict_fast, number=10000)
)
# 5.168972805004538 1.6963867129435828 0.021918574168087623 …
Run Code Online (Sandbox Code Playgroud)

python numpy keras tensorflow

10
推荐指数
2
解决办法
1758
查看次数

如何避免 Chrome 在解析此 JSON 时崩溃?

我创建了一个非常简单的网页,它只是解析一些 JSON 字符串,但不知何故浏览器总是崩溃。我使用 Chrome 80.0.3987.132。我用验证器测试了字符串,它确保它是有效的 JSON。如何调试我的代码以查看它失败的原因?有没有办法在不失败的情况下解析 JSON?

结果是 Chrome 80.0.3987.132(在 Ubuntu 上): 在此处输入图片说明

<!DOCTYPE html>
<html>
<body>

<h1>Can Chrome parse JSON?</h1>

<script>
var my_json = `{
   "base":[
      {
         "params":{
            "list":[
               {
                  "description":"bla",
                  "max":0.5,
                  "min":0.0,
                  "name":"bla",
                  "stepsize":0.01,
                  "type":"float",
                  "unit":"M"
               },
               {
                  "description":"bla",
                  "max":null,
                  "min":null,
                  "name":"bla",
                  "params":[
                     {
                        "description":"bla",
                        "max":15,
                        "min":5,
                        "name":"bla",
                        "stepsize":0.1,
                        "type":"float",
                        "unit":null
                     },
                     {
                        "description":"bla",
                        "max":15,
                        "min":0.1,
                        "name":"bla",
                        "stepsize":0.01,
                        "type":"float",
                        "unit":null
                     }
                  ],
                  "type":"ARRAY",
                  "unit":null
               }
            ]
         }
      }
   ]
}`
JSON.parse(my_json)
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

html javascript json google-chrome

6
推荐指数
1
解决办法
204
查看次数

标签 统计

google-chrome ×1

html ×1

javascript ×1

json ×1

keras ×1

numpy ×1

python ×1

tensorflow ×1