当前位置: 首页 > 知识库问答 >
问题:

Python-缩进错误:意外缩进

陶沛
2023-03-14

我不知道我犯了什么错误。只有标签,没有空间。我从本教程中获取了这段代码,http://cloudacademy.com/blog/google-prediction-api/.(我正在使用PyCharm进行开发)。

错误消息

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/ZERO/GooglePredictionApi/google.py文件"/用户/ZERO/GooglePredictionApi/google.py",第72行api=get_prediction_api()^IndentationError:意外缩进

进程已完成,退出代码为1

示例代码

import httplib2, argparse, os, sys, json
from oauth2client import tools, file, client
from googleapiclient import discovery
from googleapiclient.errors import HttpError

#Project and model configuration
project_id = '132567073760'
model_id = 'HAR-model'

#activity labels
labels = {
    '1': 'walking', '2': 'walking upstairs', 
    '3': 'walking downstairs', '4': 'sitting', 
    '5': 'standing', '6': 'laying'
}

def main():
    """ Simple logic: train and make prediction """
    try:
        make_prediction()
    except HttpError as e: 
        if e.resp.status == 404: #model does not exist
            print("Model does not exist yet.")
            train_model()
            make_prediction()
        else: #real error
            print(e)


def make_prediction():
    """ Use trained model to generate a new prediction """

    api = get_prediction_api() //error here

    print("Fetching model.")

    model = api.trainedmodels().get(project=project_id, id=model_id).execute()

    if model.get('trainingStatus') != 'DONE':
        print("Model is (still) training. \nPlease wait and run me again!") #no polling
        exit()

    print("Model is ready.")

    """
    #Optionally analyze model stats (big json!)
  analysis = api.trainedmodels().analyze(project=project_id, id=model_id).execute()
    print(analysis)
    exit()
    """

    #read new record from local file
    with open('record.csv') as f:
        record = f.readline().split(',') #csv

    #obtain new prediction
    prediction = api.trainedmodels().predict(project=project_id, id=model_id, body={
        'input': {
            'csvInstance': record
        },
    }).execute()

    #retrieve classified label and reliability measures for each class
    label = prediction.get('outputLabel')
    stats = prediction.get('outputMulti')

    #show results
    print("You are currently %s (class %s)." % (labels[label], label) ) 
    print(stats)


def train_model():
  """ Create new classification model """

    api = get_prediction_api()

    print("Creating new Model.")

    api.trainedmodels().insert(project=project_id, body={
        'id': model_id,
        'storageDataLocation': 'machine-learning-dataset/dataset.csv',
        'modelType': 'CLASSIFICATION'
    }).execute()


def get_prediction_api(service_account=True):
    scope = [
        'https://www.googleapis.com/auth/prediction',
        'https://www.googleapis.com/auth/devstorage.read_only'
    ]
    return get_api('prediction', scope, service_account)


def get_api(api, scope, service_account=True):
    """ Build API client based on oAuth2 authentication """
    STORAGE = file.Storage('oAuth2.json') #local storage of oAuth tokens
    credentials = STORAGE.get()
    if credentials is None or credentials.invalid: #check if new oAuth flow is needed
        if service_account: #server 2 server flow
            with open('service_account.json') as f:
                account = json.loads(f.read())
                email = account['client_email']
                key = account['private_key']
            credentials = client.SignedJwtAssertionCredentials(email, key, scope=scope)
            STORAGE.put(credentials)
        else: #normal oAuth2 flow
            CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
            FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS, scope=scope)
            PARSER = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser])
            FLAGS = PARSER.parse_args(sys.argv[1:])
            credentials = tools.run_flow(FLOW, STORAGE, FLAGS)

  #wrap http with credentials
    http = credentials.authorize(httplib2.Http())
    return discovery.build(api, "v1.6", http=http)


if __name__ == '__main__':
    main()

共有3个答案

皇甫夕
2023-03-14

改变

def train_model():
  """ Create new classification model """

    api = get_prediction_api()

def train_model():
    """ Create new classification model """

    api = get_prediction_api()
白信鸿
2023-03-14
import httplib2, argparse, os, sys, json
from oauth2client import tools, file, client
from googleapiclient import discovery
from googleapiclient.errors import HttpError

#Project and model configuration
project_id = '132567073760'
model_id = 'HAR-model'

#activity labels
labels = {
    '1': 'walking', '2': 'walking upstairs',
    '3': 'walking downstairs', '4': 'sitting',
    '5': 'standing', '6': 'laying'
}

def main():
    """ Simple logic: train and make prediction """
    try:
        make_prediction()
    except HttpError as e:
        if e.resp.status == 404: #model does not exist
            print("Model does not exist yet.")
            train_model()
            make_prediction()
        else: #real error
            print(e)


def make_prediction():
    """ Use trained model to generate a new prediction """

    api = get_prediction_api() //error here

    print("Fetching model.")

    model = api.trainedmodels().get(project=project_id, id=model_id).execute()

    if model.get('trainingStatus') != 'DONE':
        print("Model is (still) training. \nPlease wait and run me again!") #no polling
        exit()

    print("Model is ready.")

    """
    #Optionally analyze model stats (big json!)
  analysis = api.trainedmodels().analyze(project=project_id, id=model_id).execute()
    print(analysis)
    exit()
    """

    #read new record from local file
    with open('record.csv') as f:
        record = f.readline().split(',') #csv

    #obtain new prediction
    prediction = api.trainedmodels().predict(project=project_id, id=model_id, body={
        'input': {
            'csvInstance': record
        },
    }).execute()

    #retrieve classified label and reliability measures for each class
    label = prediction.get('outputLabel')
    stats = prediction.get('outputMulti')

    #show results
    print("You are currently %s (class %s)." % (labels[label], label) )
    print(stats)


def train_model():
    """ Create new classification model """

    api = get_prediction_api()

    print("Creating new Model.")

    api.trainedmodels().insert(project=project_id, body={
        'id': model_id,
        'storageDataLocation': 'machine-learning-dataset/dataset.csv',
        'modelType': 'CLASSIFICATION'
    }).execute()


def get_prediction_api(service_account=True):
    scope = [
        'https://www.googleapis.com/auth/prediction',
        'https://www.googleapis.com/auth/devstorage.read_only'
    ]
    return get_api('prediction', scope, service_account)


def get_api(api, scope, service_account=True):
    """ Build API client based on oAuth2 authentication """
    STORAGE = file.Storage('oAuth2.json') #local storage of oAuth tokens
    credentials = STORAGE.get()
    if credentials is None or credentials.invalid: #check if new oAuth flow is needed
        if service_account: #server 2 server flow
            with open('service_account.json') as f:
                account = json.loads(f.read())
                email = account['client_email']
                key = account['private_key']
            credentials = client.SignedJwtAssertionCredentials(email, key, scope=scope)
            STORAGE.put(credentials)
        else: #normal oAuth2 flow
            CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
            FLOW = client.flow_from_clientsecrets(CLIENT_SECRETS, scope=scope)
            PARSER = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser])
            FLAGS = PARSER.parse_args(sys.argv[1:])
            credentials = tools.run_flow(FLOW, STORAGE, FLAGS)

  #wrap http with credentials
    http = credentials.authorize(httplib2.Http())
    return discovery.build(api, "v1.6", http=http)


if __name__ == '__main__':
    main()

您在“createnewclassification model”上的缩进错误,请查看此处以了解有关python缩进编码的更多信息。

孙志
2023-03-14

这是云学院的亚历克斯。

您可以在此处找到更新的要点:https://gist.github.com/alexcasalboni/cf11cc076ad70a445612

正如其他人指出的,错误是由不一致的缩进造成的。这是一个一般的Python问题,与Google预测API或机器学习无关。

每当您发现自己处于这种情况时,我都会建议您简单地遵循PEP8约定,并将每个硬选项卡转换为空格。正如这个答案正确建议的那样,您可以通过tabnanny或正确配置代码编辑器来解决这个问题。

 类似资料:
  • 问题内容: 我是Python的新手,正在收到此错误: 在这段代码上: 问题答案: 尽管缩进错误在StackOverflow页面上很明显,但它们可能不在您的编辑器中。您在这里混合使用不同的缩进类型,1、4和8个空格。根据PEP8,您应始终使用四个空格进行缩进。您还应该避免混用制表符和空格。 我还建议您尝试使用‘ ‘命令行选项 来运行脚本,以确定何时意外混合使用制表符和空格。当然,任何体面的编辑器都可

  • 我想创建一个用户信息命令,但我仍然得到一个错误embed.set_author(name=f用户信息-{成员})索引错误:意外的缩进我不知道这是否足以理解我的错误在哪里(我只是开始编码) @客户。command()异步定义信息(ctx,成员:discord.member):

  • 问题内容: 这个问题已经在这里有了答案 : 我收到一个IndentationError。我如何解决它? (4个答案) 去年关闭。 我有一段简单的代码,我不明白我的错误来自哪里。解析器在第5行(if语句)使用意外缩进对我咆哮。有人在这里看到问题吗?我不。 问题答案: 如果您只是复制并粘贴了代码,则可以在语句所在的行上使用一个选项卡。Python将制表符解释为8个空格而不是4个空格。永远不要将制表符与

  • 这是我的model.py代码: 当我运行以下命令时: 这给我以下错误: mjrulesamrat@mjrulesamrat-Lenovo-G570:~/django\u local/first\u web$python manage.py运行服务器验证模型。。。 Traceback(最近一次调用)启动的线程中未处理的异常:文件"/usr/local/lib/python2.7/dist-包/dja

  • 问题内容: 我已经尝试过notepad ++和eclipse,但是即使如此,它仍然在第18行向我显示缩进错误。我不知道,为什么它会向我抛出这样的错误…?请帮我。 问题答案: 例如,以下是您的报价: 尝试这个:

  • 问题内容: 如何纠正python中的“意外缩进”错误? 问题答案: Python在行的开头使用空格来确定代码块的开始和结束时间。你可以获得的错误是: 意外缩进。这行代码的开头比以前的空格多,但是前面的不是子块的开头(例如if / while / for语句)。块中的所有代码行必须以完全相同的空白字符串开头。例如: 当以交互方式运行python时,这一点尤其常见:请确保在命令前不要放置任何多余的空格