Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-缩进错误:意外缩进_Python_Google Prediction - Fatal编程技术网

Python-缩进错误:意外缩进

Python-缩进错误:意外缩进,python,google-prediction,Python,Google Prediction,我不知道我犯了什么错误。只有标签,没有空间。我从本教程中获取了这段代码。(我正在使用PyCharm进行开发) 错误消息 /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/ZERO/GooglePredictionApi/google.py 文件 “/Users/ZERO/GooglePredictionApi/google.py”, 第72行 api=get\u prediction\u 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\u prediction\u api() ^缩进错误:意外缩进

进程已完成,退出代码为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()
改变


有许多缩进错误,请尝试以下操作:

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()
“创建新分类模型”上的缩进错误
只需了解更多有关python缩进编码的信息。

也许错误在于:

def列_模型(): “”“创建新的分类模型”“”


应该正确缩进,但其他人指出了其他缩进错误,只要在编写代码时始终检查缩进,否则可能会弄得一团糟,无法找出错误的位置。

这里是来自CloudAcademy的Alex

您可以在此处找到更新的要点:

正如其他人指出的,错误是由不一致的缩进造成的。这是一个,与谷歌预测API或机器学习无关


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

`“创建新分类模型”`` docstring缩进2个空格,应该缩进4个空格。如果“第72行中出现意外缩进”,您可能希望修复第72行的缩进,不是吗。可能有一个制表符,其中应该有空格,反之亦然。在PyCharm中应该有函数“将制表符转换为空格”-我得到了打印(“创建新模型”)^indentation错误:unindent不匹配任何外部缩进级别。不要复制和粘贴我写的内容,因为这样一来,空格和制表符可能会混合使用。修复代码中的缩进:如果您一直使用tab,那么还可以在“创建新分类模型”之前插入一个选项卡。顺便问一下:好的风格是使用四个空格的缩进代替制表符。两者之间有什么区别?niyasc lol,不多,但网站让我无法显示正确的缩进。我编辑了缩进,注意到缩进是不正确的,应该更正,仅此而已
def train_model():
    """ Create new classification model """

    api = get_prediction_api()
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()
api = get_prediction_api()

print("Creating new Model.")