繁体   English   中英

Azure Flask Web App上的内部服务器错误

[英]Internal Server Error on Azure Flask Web App

我创建了Flask Web应用程序,该应用程序托管在Azure上,并带有Dreamspark订阅。 它使用诸如Numpy,Scipy和Theano之类的库。

当我使用简单的Theano计算部署应用程序时,它可以完美运行。 但是,当我将代码更改为更复杂的Theano计算时,出现内部服务器错误。

这是示例代码。 当我调用simpleFunction(类似于Theano函数的求和)时,它可以工作,但是当调用complexFunction(类似于图像分类计算)时,则创建内部服务器错误:

from flask import Flask
app = Flask(__name__)
wsgi_app = app.wsgi_app

from fileContainingTheanoCode import simpleFunction, complexFunction

@app.route('/')
def hello():
    result = simpleFunction()
    thisStr = str(result)
    return   """<html>
                    <head>
                        <title>Test website</title>
                    </head>
                    <body>
                        <h1>"""+thisStr+"""</h1>
                    </body>
                </html>"""


if __name__ == '__main__':
    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    app.run(HOST, PORT)

为了清楚起见,以下是文件theanoCode.py的代码(它是卷积神经网络分类器,使用加载模块从文件中读取mnist数据集):

# Import Libraries----------------------------------------------------------
import os
import sys
import pickle
import theano
import numpy as np
from theano import tensor as T
from theano.tensor.nnet.conv import conv2d
from theano.tensor.signal.downsample import max_pool_2d
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
srng = RandomStreams()
import load

testSize = 10
trainSize = 2
#---------------------------------------------------------------------------

# Constants-----------------------------------------------------------------
weightsFile = 'mnist.weights'
#---------------------------------------------------------------------------

# Model---------------------------------------------------------------------
# Stuff variable into numpy array with theano float datatype
def floatX(X):
    return np.asarray(X, dtype=theano.config.floatX)


# Initialize weights randomly
def init_weights(shape):
    return theano.shared(np.asarray(np.random.randn(*shape) * 0.01, dtype=theano.config.floatX),borrow=True)


# ReLU - rectify linear function with Theano
def rectify(X):
    return T.maximum(X, 0.)


# Softmax operation
def softmax(X):
    e_x = T.exp(X - X.max(axis=1).dimshuffle(0, 'x'))
    return e_x / e_x.sum(axis=1).dimshuffle(0, 'x')


# Implements random chance of ignoring a neuron output during training
def dropout(X, p=0.):
    if p > 0:
        retain_prob = 1 - p
        X *= srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX)
        X /= retain_prob
    return X


# Gradient Descent with regularization - parameter reduction
def RMSprop(cost, params, lr=0.001, rho=0.9, epsilon=1e-6):
    grads = T.grad(cost=cost, wrt=params)
    updates = []
    for p, g in zip(params, grads):
        acc = theano.shared(p.get_value() * 0.)
        acc_new = rho * acc + (1 - rho) * g ** 2
        gradient_scaling = T.sqrt(acc_new + epsilon)
        g = g / gradient_scaling
        updates.append((acc, acc_new))
        updates.append((p, p - lr * g))
    return updates


# Constructs the model
def model(X, w1, w2, w3, w4, p_drop_conv, p_drop_hidden):
    l1a = rectify(conv2d(X, w1, border_mode='full'))
    l1 = max_pool_2d(l1a, (2, 2),ignore_border=False)
    l1 = dropout(l1, p_drop_conv)

    l2a = rectify(conv2d(l1, w2))
    l2 = max_pool_2d(l2a, (2, 2),ignore_border=False)
    l2 = dropout(l2, p_drop_conv)

    l3a = rectify(conv2d(l2, w3))
    l3b = max_pool_2d(l3a, (2, 2),ignore_border=False)
    l3 = T.flatten(l3b, outdim=2)
    l3 = dropout(l3, p_drop_conv)

    # Fully connected Layer
    l4 = rectify(T.dot(l3, w4))
    l4 = dropout(l4, p_drop_hidden)

    # Classify the Output
    pyx = softmax(T.dot(l4, w_o))
    return l1, l2, l3, l4, pyx


# Load the data (tr = training, te = test)
trX, teX, trY, teY = load.mnist(ntrain=trainSize, ntest=testSize, onehot=True)


# Reshape training set to be 4-dimensional
# negative value is to get ordering right (rather than mirror image)
# Second parameter is color channels
trX = trX.reshape(-1, 1, 28, 28)
teX = teX.reshape(-1, 1, 28, 28)

# Input variables
X = T.dtensor4()
Y = T.fmatrix()


# WEIGHTS
if os.path.isfile(weightsFile):
    # Go get saved weights from file
    [w1, w2, w3, w4, w_o] = pickle.load(open(weightsFile,'rb'))
else:
    # Initialize all layer weights
    # (no. Inputs, no. Outputs, filter height, filter width)
    # ver isto outra vez, minuto 48
    w1 = init_weights((32, 1, 3, 3)) # 1 = num canais de cada imagem (cor)
    w2 = init_weights((64, 32, 3, 3))
    w3 = init_weights((128, 64, 3, 3))
    w4 = init_weights((128 * 3 * 3, 625))
    w_o = init_weights((625, 10)) # from fully connected layer to classifier


# This sets up the model graph and some vars for noise, which are the internal neurons
noise_l1, noise_l2, noise_l3, noise_l4, noise_py_x = model(X, w1, w2, w3, w4, 0.2, 0.5)

# No dropping neurons...so this will be used for prediction
l1, l2, l3, l4, py_x = model(X, w1, w2, w3, w4, 0., 0.)

# This makes predictions
y_x = T.argmax(py_x, axis=1)

# Compile prediction function - here named complexFunction
complexFunction = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True)

这是详细的错误消息:

Event: MODULE_SET_RESPONSE_ERROR_STATUS
ModuleName  FastCgiModule
Notification    EXECUTE_REQUEST_HANDLER
HttpStatus  500
HttpReason  INTERNAL SERVER ERROR
HttpSubStatus   0
ErrorCode   The operation completed successfully.
 (0x0)

这是事件日志:

</Data></EventData></Event><Event><System><Provider Name="ASP.NET 4.0.30319.0"/><EventID>1325</EventID><Level>3</Level><Task>0</Task><Keywords>Keywords</Keywords><TimeCreated SystemTime="2016-06-05T19:34:20Z"/><EventRecordID>1604538437</EventRecordID><Channel>Application</Channel><Computer>RD000D3A218E0C</Computer><Security/></System><EventData><Data>An unhandled exception occurred and the process was terminated.

Application ID: /LM/W3SVC/1568611192/ROOT

Process ID: 647864

Exception: System.Configuration.ConfigurationErrorsException

Message: Couldn't find type for class Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.

StackTrace:    at System.Diagnostics.TraceUtils.GetRuntimeObject(String className, Type baseType, String initializeData)
   at System.Diagnostics.TypedElement.BaseGetRuntimeObject()
   at System.Diagnostics.ListenerElement.GetRuntimeObject()
   at System.Diagnostics.ListenerElementsCollection.GetRuntimeObject()
   at System.Diagnostics.TraceInternal.get_Listeners()
   at System.Diagnostics.TraceInternal.WriteLine(String message)
   at System.Diagnostics.Debug.WriteLine(String message)
   at Microsoft.Web.Compilation.Snapshots.SnapshotHelper.TakeSnapshotTimerCallback(Object stateInfo)
   at System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.TimerQueue.AppDomainTimerCallback()</Data></EventData></Event><Event><System><Provider Name=".NET Runtime"/><EventID>1026</EventID><Level>0</Level><Task>0</Task><Keywords>Keywords</Keywords><TimeCreated SystemTime="2016-06-05T19:34:20Z"/><EventRecordID>1604538453</EventRecordID><Channel>Application</Channel><Computer>RD000D3A218E0C</Computer><Security/></System><EventData><Data>Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Configuration.ConfigurationErrorsException
   at System.Diagnostics.TraceUtils.GetRuntimeObject(System.String, System.Type, System.String)
   at System.Diagnostics.TypedElement.BaseGetRuntimeObject()
   at System.Diagnostics.ListenerElement.GetRuntimeObject()
   at System.Diagnostics.ListenerElementsCollection.GetRuntimeObject()
   at System.Diagnostics.TraceInternal.get_Listeners()
   at System.Diagnostics.TraceInternal.WriteLine(System.String)
   at System.Diagnostics.Debug.WriteLine(System.String)
   at Microsoft.Web.Compilation.Snapshots.SnapshotHelper.TakeSnapshotTimerCallback(System.Object)
   at System.Threading.TimerQueueTimer.CallCallbackInContext(System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.TimerQueueTimer.CallCallback()
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.TimerQueue.AppDomainTimerCallback()

</Data></EventData></Event></Events>

导致theano问题的原因很多,例如多线程,使用GPU,内存限制等。但是根据代码和错误信息,我不确定原因是什么。

我建议您可以尝试参考theano文档“ 调试Theano:常见问题和故障排除 ”和文章“ Azure Web App沙箱 ”,以找出由什么引起的真正问题。

您可以共享complexFunction的代码吗? 我认为这对于分析问题非常有帮助,甚至尝试重现它以找出解决方案。


更新

根据您的代码和事件日志,我认为有两个可能的原因导致了此问题。

  1. 一些代码逻辑错误导致内部服务器错误,但是如果代码在本地运行良好,请忽略这种可能性。

  2. 您的Web应用程序的配置不正确,例如web.config ,请参阅web.config部分以检查其配置是否正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM