Python - IndentationError: неожиданный отступ

Я не знаю, какие ошибки совершил. Только табуляция, без пробела. Я взял этот код из этого руководства, 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()

person Mohammad Nurdin    schedule 27.11.2015    source источник
comment
`Создать новую модель классификации` Строка документации имеет отступ в два пробела, он должен быть с отступом в четыре.   -  person Łukasz Rogalski    schedule 27.11.2015
comment
Что ж, если в строке 72 есть неожиданный отступ, вы можете исправить отступ в строке 72, не так ли. Скорее всего, есть вкладка, где должны быть пробелы или (надеюсь, нет) наоборот.   -  person decltype_auto    schedule 27.11.2015
comment
В PyCharm должна быть функция преобразования табуляции в пробелы - stackoverflow.com/questions/11816147/   -  person furas    schedule 27.11.2015


Ответы (5)


Вот Алекс из CloudAcademy.

Вы можете найти обновленную суть здесь: https://gist.github.com/alexcasalboni/cf11cc076ad70a445612

Как указывали другие, ошибка связана с несогласованным отступом. Это общая проблема Python, не связанная с Google Prediction API или машинное обучение.

Всякий раз, когда вы попадаете в такую ​​ситуацию, я бы рекомендовал просто следовать Соглашения PEP8 и преобразовать каждую жесткую табуляцию в пробелы. Как правильно указано в этом ответе, вы можете решить проблему с помощью tabnanny или правильно настроив свой код. редактор.

person alexcasalboni    schedule 02.12.2015

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

У вас был неправильный отступ при создании новой модели классификации. Чтобы узнать больше о кодировании с отступом, посмотрите здесь питона.

person user5603723    schedule 27.11.2015

Изменять

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

    api = get_prediction_api()

to

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

    api = get_prediction_api()
person elzell    schedule 27.11.2015
comment
Я получил печать (Создание новой модели). ^ IndentationError: unindent не соответствует ни одному внешнему уровню отступа. - person Mohammad Nurdin; 27.11.2015
comment
Не копируйте и не вставляйте то, что я написал, потому что тогда пробелы и табуляции могут смешаться. Исправьте отступ в коде: если вы используете табуляцию полностью, то также вставьте табуляцию перед созданием новой модели классификации. Кстати: хороший стиль - использовать отступы в четыре пробела вместо табуляции. - person elzell; 27.11.2015

Было много ошибок с отступом, попробуйте следующее:

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()
person pythad    schedule 27.11.2015

возможно виновата в этом:

def train_model (): "" "Создать новую модель классификации" ""

api = get_prediction_api()

print("Creating new Model.")

должны быть правильно с отступом, но другие указали на другие ошибки отступов, просто проверяйте отступы всегда, когда вы кодируете, иначе может быть беспорядок, чтобы выяснить, где это неправильно.

person AbdulWahid    schedule 27.11.2015
comment
В чем разница между ними? - person niyasc; 27.11.2015
comment
niyasc lol, не так много, но веб-сайт не позволяет мне показывать правильный отступ, в любом случае я редактировал, чтобы отметить, что отступ там неправильный и должен быть исправлен, вот и все - person AbdulWahid; 27.11.2015