Python - IndentationError:意外缩进

时间:2015-11-27 08:57:53

标签: python google-prediction

我不知道自己犯了什么错误。只有标签,没有空格。我从本教程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()

5 个答案:

答案 0 :(得分:3)

这是来自CloudAcademy的Alex。

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

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

每当您发现自己处于这种情况时,我建议您只需按照PEP8 conventions并将每个硬标签转换为空格。正如this answer正确建议的那样,您可以使用 tabnanny 或正确配置代码编辑器来解决问题。

答案 1 :(得分:0)

更改

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

    api = get_prediction_api()

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

    api = get_prediction_api()

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

<div class="icon-several-lines">
    <img class="image" src="http://lorempixum.com/25/25/abstract" alt="" />
    <span class="info">
     <p><span>test test test test test test</span></p>
     <p><span>test test test test test test</span></p>
     <p><span>test test test test test test</span></p>
    </span>
</div>

<div class="icon-several-lines">
    <img class="image" src="http://lorempixum.com/25/25/abstract" alt="" />
    <span class="info">
     <p><span>test test test test test test</span></p>
     <p><span>test test test test test test</span></p>
    </span>
</div>

<div class="icon-several-lines">
    <img class="image" src="http://lorempixum.com/25/25/abstract" alt="" />
    <span class="info">
     <p><span>test test test test test test</span></p>

    </span>
</div>

你错了#34;&#34;&#34;创建新的分类模型&#34;&#34;&#34; 只需查看here即可了解有关python缩进编码的更多信息。

答案 4 :(得分:0)

也许错误在于:

def train_model():   &#34;&#34;&#34;创建新的分类模型&#34;&#34;&#34;

api = get_prediction_api()

print("Creating new Model.")

应该正确缩进,但是其他人已经指出了其他缩进错误,只需在编码时检查缩进,否则可能会弄清楚它在哪里出错。