2015-11-27 193 views
2

我到底在幹什麼,我不知道我做了什麼錯誤。只有標籤,沒有空間。我從本教程中獲取該代碼,http://cloudacademy.com/blog/google-prediction-api/。 (順便說一下,我正在使用PyCharm進行開發)。Python - IndentationError:意想不到的縮進

錯誤消息

/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

Process finished with exit code 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() 

請指點。謝謝。

+1

''「」創建新的分類模型「」「'docstring縮進2個空格,它應該縮進4個。 –

+0

好吧 - 如果第72行出現「意外縮進」,則可能需要修復第72行的縮進,是嗎。可能有一個選項卡應該有空格或(希望不是)反之亦然。 –

+0

在PyCharm應該是「將製表符轉換爲空格」函數 - http://stackoverflow.com/questions/11816147/pycharm-convert-tabs-to-spaces-automatically – furas

回答

0

變化

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

    api = get_prediction_api() 

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

    api = get_prediction_api() 
+0

我得到了print(「Creating new Model。」) ^ IndentationError:unindent不匹配任何外部縮進級別。 –

+0

請勿複製和粘貼我寫的內容,因爲空格和製表符可能會混在一起。在你的代碼中修改縮進:如果你一直使用標籤,那麼在「」「創建新的分類模型」「」之前插入一個標籤。順便說一句:好的風格是因此使用四個空間縮進而不是製表符。 – elzell

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() 
0
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縮進編碼的信息。

0

也許故障是這樣的:

高清train_model(): 「」「創建新的分類模型‘’」

api = get_prediction_api() 

print("Creating new Model.") 

應進行適當的縮進,但其他人指出其他縮進錯誤,只要在您編碼時檢查您的縮進,否則可能會弄得亂七八糟,找出錯誤的位置。

+0

兩者有什麼區別? – niyasc

+0

niyasc哈哈,沒有太多,但網站正在使我無法顯示正確的縮進無論如何,我編輯注意,縮進不正確,應該糾正,這就是全部 – AbdulWahid

3

這是來自CloudAcademy的Alex。

你可以找到更新的要點在這裏:https://gist.github.com/alexcasalboni/cf11cc076ad70a445612

正如其他人所指出的,錯誤是由於不一致的縮進。這是一個general Python problem,與Google Prediction API或機器學習無關。

每當你發現自己處於這種情況下,我會建議你只需按照PEP8 conventions的方式將每個硬標籤轉換爲空格。正如this answer正確建議,您可以通過tabnanny或通過正確配置您的代碼編輯器來解決問題。

相關問題