简体   繁体   English

从Python到PHP-Azure机器学习

[英]Python to PHP - Azure Machine Learning

Hi im trying to translate this python script to php. 嗨,我试图将这个python脚本翻译成php。 I don't have much knowledge of Python and limited for PHP. 我对Python的了解不多,并且对PHP的了解有限。

The python script is: python脚本是:

import urllib2
import json 

data =  {
    "Inputs": {
         "input1": {
             "ColumnNames": ["Client_ID"],
             "Values": [ [ "0" ], [ "0" ], ]
         },
     },
     "GlobalParameters": {}
}

body = str.encode(json.dumps(data))

url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14b17422435984943d51b5957ec7/execute?api-version=2.0&details=true'
api_key = 'abc123'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

req = urllib2.Request(url, body, headers) 

try:
    response = urllib2.urlopen(req)
    result = response.read()
    print(result) 
except urllib2.HTTPError, error:
    print("The request failed with status code: " + str(error.code))
    print(error.info())
    print(json.loads(error.read()))                 

In a bid to try and convert it myself, here is what I have done so far: 为了尝试自己进行转换,这是我到目前为止所做的:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$data = array(
    'Inputs'=> array(
        'input1'=> array(
            'ColumnNames' => ["Client_ID"],
            'Values' => [ [ "0" ], [ "0" ], ]
        ),
    ),
    'GlobalParameters'=> array()
);

$body = json_encode($data);

$url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14d17425435984943d41a5957ec7/execute?api-version=2.0&details=true';
$api_key = 'abc123'; 
$headers = array('Content-Type'=>'application/json', 'Authorization'=>('Bearer '+ $api_key));


$curl = curl_init();

curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);


$result = curl_exec($curl);
var_dump($result);

im sure I have got lots wrong but would appreciate the help. 即时通讯我确定我做错了很多,但会感谢您的帮助。

thanks 谢谢

I just had to do this myself and though I'd provide an answer for you. 我只需要自己做,尽管我会为您提供答案。 If you're going to talk to Azure's ML platform using php, you need to build your CURL call like this: 如果要使用php与Azure的ML平台进行对话,则需要构建CURL调用,如下所示:

$data = array(
  'Inputs'=> array(
      'input1'=> array(
          'ColumnNames' => array("header1", "header2", "header3"),
          'Values' => array( array("value1" ,  "value2" ,  "value3"))
      ),
  ),
  'GlobalParameters'=> null
);

$body = json_encode($data);

$url = 'your-endpoint-url';
$api_key = 'your-api-key'; 
$headers = array('Content-Type: application/json', 'Authorization:Bearer ' . $api_key, 'Content-Length: ' . strlen($body));

$this->responseArray['body'] = $body;


$curl = curl_init($url); 
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);


$result = curl_exec($curl);

Of all the places to get hung up, it was on the GlobalParameters for me, and is for you, too. 在所有挂断电话的地方,对我来说,它都在GlobalParameters上,对您也一样。 You need this instead: 您需要此:

GlobalParameters => null

This generates the following JSON 这将生成以下JSON

GlobalParameters: {}

whereas

GlobalParameters => array()

gives

GlobalParameters: []

it's a subtle distinction, but enough to make Azure throw a hissy fit. 这是一个微妙的区别,但足以使Azure显得格格不入。

I didn't test using your curl_setopt functions and instead used what I've included in my example. 我没有使用您的curl_setopt函数进行测试,而是使用了示例中包含的内容。 I'm assuming it will work using the curl_setopt s you have, but I don't know for sure. 我假设它将使用您拥有的curl_setopt起作用,但是我不确定。

I had some trouble adapting this perfectly, and I wanted to be able to easily work with JSON & Guzzle. 我很难完全适应此问题,并且希望能够轻松使用JSON&Guzzle。 Below is the solution that I built. 以下是我构建的解决方案。

First is the function for making the actual call to Azure. 首先是用于实际调用Azure的功能。 Note that Guzzle wants your URL to be split into the domain and URI pieces. 请注意,Guzzle希望将您的URL分为域和URI。

This should all be in your .env file (if you're using Laravel at least). 这应该全部在您的.env文件中(如果您至少使用Laravel)。 AZURE_BASE=https://ussouthcentral.services.azureml.net

AZURE_URL=/workspaces/[[YOUR_STUFF_HERE]]/services/[[YOUR_STUFF_HERE]]/execute?api-version=2.0&format=swagger

AZURE_PRIMARY_KEY=[[YOUR_KEY]]

use GuzzleHttp\Client;

public function learn () {

    $client = new Client([
        'base_uri' => env('AZURE_BASE'),
        'timeout'  => 2.0,
    ]);
    $headers = [
        'Authorization' => 'Bearer ' .env('AZURE_PRIMARY_KEY'),        
        'Accept'        => 'application/json',
        'Content-Type' => 'application/json'
    ];

    $data = $this->test_data();
    $body = json_encode($data);

    $response = $client->request('POST', env('AZURE_URL'), [
        'headers' => $headers,
        'body' => $body
    ]);


    return $response;

}

As other answers have noted, the data setup is very touchy. 正如其他答案所指出的那样,数据设置非常敏感。 new \\stdClass is the key here, as we need to end up with a JSON Object ( {} ) not an array ( [] ). new \\stdClass是这里的关键,因为我们需要以JSON对象( {} )而不是数组( [] )结尾。 stdClass creates that empty object for us. stdClass为我们创建该空对象。

function test_data () {
    return array(
        'Inputs'=> array(
            'input1'=> array(
                [
                'DESC' => "",   
                '2-week-total'=> "1",   
                'last-week'=> "1",   
                'this-week'=> "1",   
                'delta'=> "1",   
                'normalized delta'=> "1",   
                'delta-percent'=> "1",   
                'high-total-delta'=> "1",   
                'high-total-amt'=> "1",   
                'role'=> ""
                ]
            ),
        ),
        'GlobalParameters'=> new \stdClass,
    );
}

Now when you call ->learn() , you'll get back some nice JSON to do what you need. 现在,当您调用->learn() ,您将获得一些不错的JSON以执行所需的操作。

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

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