简体   繁体   English

Python-IndentationError:意外缩进

[英]Python - IndentationError: unexpected indent

I don't know what mistakes I've done. 我不知道我犯了什么错误。 Only tab, no space. 仅制表符,无空格。 I grab this code from this tutorial, http://cloudacademy.com/blog/google-prediction-api/ . 我从本教程http://cloudacademy.com/blog/google-prediction-api/中获取了这段代码。 (I'm using PyCharm for development). (我正在使用PyCharm进行开发)。

Error message 错误信息

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/ZERO/GooglePredictionApi/google.py File "/Users/ZERO/GooglePredictionApi/google.py", line 72 api = get_prediction_api() ^ IndentationError: unexpected indent /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:意外缩进

Process finished with exit code 1 流程以退出代码1完成

Sample code 样例代码

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 is Alex from CloudAcademy. 这是CloudAcademy的Alex。

You can find the updated gist here: https://gist.github.com/alexcasalboni/cf11cc076ad70a445612 您可以在这里找到更新的要点: https//gist.github.com/alexcasalboni/cf11cc076ad70a445612

As others pointed out, the error is due to an inconsistent indentation. 正如其他人指出的那样,该错误是由于缩进不一致引起的。 This is a general Python problem , not related to Google Prediction API or Machine Learning. 这是一个一般的Python问题 ,与Google Prediction API或机器学习无关。

Whenever you find yourself in such a situation, I would recommend to simply follow PEP8 conventions and convert every hard tab into spaces. 每当您遇到这种情况时,我建议您只需遵循PEP8约定并将每个硬标签都转换为空格。 As this answer correctly suggested, you can fix the problem with tabnanny or by properly configuring your code editor. 如正确答案所示 ,您可以使用tabnanny或通过正确配置代码编辑器来解决问题。

Change 更改

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

    api = get_prediction_api()

to

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

    api = get_prediction_api()

There were many indentation errors, try this: 有许多缩进错误,请尝试以下操作:

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()
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()

You had wrong indent on """ Create new classification model """ Just look here to know more about indent coding of python. 您在“”“上缩进错了,创建新的分类模型”“”只是在这里了解有关python缩进编码的更多信息。

maybe the fault is at this: 也许是这个错误:

def train_model(): """ Create new classification model """ def train_model():“”“创建新的分类模型”“”

api = get_prediction_api()

print("Creating new Model.")

should be properly indented but others have pointed out other indentation errors, just check your indentations always as you code by otherwise it can be a mess to figure out where it is wrong. 应该正确地缩进,但是其他人指出了其他缩进错误,只要在编写代码时始终检查缩进,否则弄乱了哪里是错的。

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

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