【问题标题】:Python - IndentationError: unexpected indentPython - IndentationError:意外缩进
【发布时间】:2015-11-27 08:57:53
【问题描述】:

我不知道自己犯了什么错误。只有制表符,没有空格。我从本教程中获取此代码,http://cloudacademy.com/blog/google-prediction-api/。 (我正在使用 PyCharm 进行开发)。

错误信息

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/ZERO/GooglePredictionApi/google.py 文件 "/Users/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()

【问题讨论】:

  • ` """ 创建新的分类模型 """` 文档字符串缩进2个空格,应该缩进4个。
  • 好吧-如果“第 72 行出现意外缩进”,您可能想要修复第 72 行的缩进,不是吗。可能有一个标签应该有空格,或者(希望不是)反之亦然。
  • 在 PyCharm 中应该是“将制表符转换为空格”的功能 - stackoverflow.com/questions/11816147/…

标签: python google-prediction


【解决方案1】:

这是来自 CloudAcademy 的 Alex。

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

正如其他人指出的那样,错误是由于缩进不一致。这是general Python problem,与 Google 预测 API 或机器学习无关。

每当您遇到这种情况时,我建议您只需关注PEP8 conventions 并将每个硬制表符转换为空格。正如this answer 正确建议的那样,您可以使用 tabnanny 或通过正确配置代码编辑器来解决问题。

【讨论】:

    【解决方案2】:
    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()
    

    您在“”“创建新的分类模型”“”上有错误的缩进 看here了解更多关于python的缩进编码。

    【讨论】:

      【解决方案3】:

      改变

      def train_model():
        """ Create new classification model """
      
          api = get_prediction_api()
      

      def train_model():
          """ Create new classification model """
      
          api = get_prediction_api()
      

      【讨论】:

      • 我得到了 print("Creating new Model.") ^ IndentationError: unindent 不匹配任何外部缩进级别。
      • 不要复制粘贴我写的内容,因为这样可能会混用空格和制表符。修复代码中的缩进:如果你一直使用制表符,那么还要在“””之前插入一个制表符创建新的分类模型“””。顺便说一句:好的风格是使用四个空格缩进而不是制表符。
      【解决方案4】:

      有很多缩进错误,试试这个:

      import httplib2
      import argparse
      import os
      import sys
      import 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()
      
          print("Fetching model.")
      
          model = api.trainedmodels().get(project=project_id, id=model_id).execute()
      
          if model.get('trainingStatus') != 'DONE':
              # no polling
              print("Model is (still) training. \nPlease wait and run me again!")
              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()
          # check if new oAuth flow is needed
          if credentials is None or credentials.invalid:
              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()
      

      【讨论】:

        【解决方案5】:

        可能是这个问题:

        定义训练模型(): """创建新的分类模型"""

        api = get_prediction_api()
        
        print("Creating new Model.")
        

        应该正确缩进,但其他人指出了其他缩进错误,只需在编写代码时始终检查缩进,否则可能很难找出错误所在。

        【讨论】:

        • 两者有什么区别?
        • niyasc 大声笑,不多,但网站让我无法显示正确的缩进,我编辑指出缩进不正确,应该更正,仅此而已
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-04
        • 2022-08-20
        • 2020-12-17
        • 2011-04-24
        • 1970-01-01
        • 2012-05-01
        相关资源
        最近更新 更多