也不知道百度什么时候退出了一个AI开发平台,提供了很多接口,刚好和实验室的项目和很多的是相关的,就来看看百度AI平台上效果如何。
首先在你的应用列表创建一个应用,创建完成后会生成一个AppID、API Key、Secret Key。
然后在git bash输入:curl -i -k ‘https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】’
把你生成的API Key和Secret Key放到上面命令行对应的位置即可,成功会你会得到一个access_token,这个acess_token在后面代码会用到。
写一个获得词向量相似度的接口WordVecTest
package baidu.ai;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by GEKL on 2018/1/22.
* 词义相似度接口
*/
public class WordVecTest {
// 使用这份代码需要改变一下access_token,换成你的即可
private static String wordVcestrURL = "https://aip.baidubce.com/rpc/2.0/nlp/v2/word_emb_sim?charset=UTF-8&access_token=24.62d29c70ad9056930d2e6c8437397385.2592000.1519178831.282335-10726137";
public static String getSimilarity(String body) throws Exception{
URL url = new URL(wordVcestrURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求头参数
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
//添加body参数,body参数需要以流的方式写入
System.out.println(body);
OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
os.write(body);
os.flush();
os.close();
//发送链接
connection.connect();
//接受、解析返回结果
InputStream in = connection.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for ( int len = 0; (len = in.read(buffer)) > 0;) {
baos.write(buffer, 0, len);
}
String returnValue = new String(baos.toByteArray(), "utf-8" );
//关闭流
baos.flush();
baos.close();
in.close();
connection.disconnect();
//返回结果
return returnValue;
}
}
测试类BaiduAITest
package baidu.ai;
import com.baidu.aip.nlp.AipNlp;
/**
* Created by GEKL on 2018/1/22.
*/
public class BaiduAITest {
public static String wordVecTest(String body) throws Exception{
return WordVecTest.getSimilarity(body);
}
public static void main(String[] args) throws Exception{
//词向量相似度接口测试
String body = "{\"word_1\":\"上海\",\"word_2\":\"北京\"}";
System.out.println(wordVecTest(body));
}
}
输出结果:
{"word_1":"上海","word_2":"北京"}
{"log_id": 613982232145937444, "score": 0.456862, "words": {"word_2": "北京", "word_1": "上海"}}
Process finished with exit code 0
如果觉得上面的代码复杂或者运行不了的话,可以直接到官网下载对应的JDK
https://ai.baidu.com/sdk#nlp,平台都已经封装好了。只需要下面几行代码。
public class AipNlpTest {
public static void main(String[] args) {
AipOcr client = new AipOcr("你的Appid", "你的apikey", "你的sercetKey");
String word1 = "北京";
String word2 = "上海";
// 词义相似度
JSONObject res = client.wordSimEmbedding(word1, word2, null);
System.out.println(res.toString(2));
}
}
不足的就是acess_token是只有一个月的有效期,并且不支持并发。