怎样从gdelt上下载数据_Gdelt数据库初探
一、Gdelt数据库GDELT(www.gdeltproject.org)每时每刻监控着每个国家的几乎每个角落的100多种语言的新闻媒体--印刷的、广播的和web形式的,识别人员、位置、组织、数量、主题、数据源、情绪、报价、图片和每秒都在推动全球社会的事件,GDELT为全球提供了一个自由开放的计算平台。GDELT主要包含两大数据集:Event Database(事件数据库)、Global Know
一、Gdelt数据库
GDELT(www.gdeltproject.org)每时每刻监控着每个国家的几乎每个角落的100多种语言的新闻媒体--印刷的、广播的和web形式的,识别人员、位置、组织、数量、主题、数据源、情绪、报价、图片和每秒都在推动全球社会的事件,GDELT为全球提供了一个自由开放的计算平台。
GDELT主要包含两大数据集:Event Database(事件数据库)、Global Knowledge Graph (GKG,全球知识图谱),记录了从1969年至今的新闻,并于每十五分钟更新一次数据。
Event Database记录了包含事件发生时间、事件参与者等61个字段,其中事件中参与者身份如下表所示:
EventBaseCode字段记录了事件的类别,共分为20大类,通过对类别的识别可以有效的筛选出需要分析的信息。
二、项目列表
本文将介绍以下几个任务(根据项目需求持续更新)通过Gdelt实现在规定时间内对指定关键词新闻的数量进行统计,并绘制图像
对Gdelt数据实现基于LSTM的时间序列预测
(1)通过Gdelt实现在规定时间内对指定关键词新闻的数量进行统计,并绘制图像
因为数据量巨大,本机难以处理。在这里,我们可以通过Gdelt提供的GAS对数据进行预处理。GAS包括了事件浏览器、事件网络、事件时间线、事件热力图、GKG网络、GKG时间线、GKG热力图、GKG浏览等功能。The Global Database of Events, Language, and Toneanalysis.gdeltproject.org
使用GKG Exporter模块初步筛选关键词对应新闻,官方介绍如下Searches all GKG records and returns matching GKG records and a list of source URLs. Intended primarily for advanced users with extensive scripting experience.
输出的数据包含以下两个文件Source List Produces a list of all of the source news articles for all of the matching GKG records.
Matching GKG Records Returns the raw CSV GKG records that matched your search criteria - it can generate extremely large files, but is useful to filter down the entire GKG to just the records matching your needs.
输入邮箱、时间范围、关键词,提交后就可以等待反馈的邮件,根据邮件中的下载地址就可以下载预处理后的数据了。
通过pandas以table方式读入数据
import pandas as pd
df=pd.read_table(file,engine='python')
预览数据如图
Locations列涉及到地域,只要拆分保留最后一个字符串即为国家。
file="gkg.txt"
keyword="Locations"
df[keyword]=df[keyword].str.split('#',expand=True)[1]
t=df[keyword].str.split(',',expand=True)
for i in t:
if t[2][i]!=None:
t[1]=t[2]
if t[1][i]!=None:
t[0]=t[1]
df[keyword]=t
统计Locations列相同项个数
location=df[keyword].value_counts()
将结果打印并输出
print ("keyword="+keyword)
print ("Country/count")
print (location)
location.to_csv("output.csv")
得出结果
绘制图像
import matplotlib.pyplot as plt
from pylab import mpl
from dateutil.parser import parse
mpl.rcParams['font.sans-serif'] = ['SimHei']
Keyword="Locations"
Country="China"
Rollsize=5
df=pd.read_table(File,engine='python')
date_standard=0
for i in df.Date:
df.Date[date_standard]=parse(str(i))
date_standard=date_standard+1
#按年
date=df[["Date",Keyword]]
date.dropna(axis=0, how='any', inplace=True)
date=date["Date"].value_counts()
date=date.sort_index(axis=0, ascending=True)
date.to_csv("Date.csv,header=1")
plt.plot(date,label='原始图像')
plt.plot(date.rolling(Rollsize).mean(),label="含滑动窗体图像")
plt.xlabel('Date')
plt.ylabel('Count')
plt.title('新闻数据量统计折线图')
plt.legend()
plt.savefig('World.png')
plt.show()
#按国家
country=df[["Date",Keyword]]
country.dropna(axis=0, how='any',inplace=True)
filter_data=country[country[Keyword].isin([Country])]
filter_data=filter_data["Date"].value_counts()
filter_data=filter_data.sort_index(axis=0, ascending=False)
plt.plot(filter_data,label='原始图像')
plt.plot(filter_data.rolling(Rollsize).mean(),label="含滑动窗体图像")
plt.xlabel('Date')
plt.ylabel('Count')
plt.title(Country+'新闻数据量统计折线图')
plt.legend()
plt.savefig(Country+'.png')
plt.show()
效果如图
(二)对Gdelt数据实现基于LSTM的时间序列预测
数据样式如下In [1]:date.head(10)
Out[1]:
2018-01-01 1
2018-01-02 1
2018-01-03 1
2018-01-05 1
2018-01-08 1
2018-01-10 1
2018-01-11 1
2018-01-14 1
2018-01-15 1
2018-01-16 2
Name: Date, dtype: int64
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Activation
def create_model():
model = Sequential()
#输入数据的shape为(n_samples, timestamps, features)
#隐藏层设置为256, input_shape元组第二个参数1意指features为1
#下面还有个lstm,故return_sequences设置为True
model.add(LSTM(units=256,input_shape=(None,1),return_sequences=True))
model.add(LSTM(units=256))
#后接全连接层,直接输出单个值,故units为1
model.add(Dense(units=1))
model.add(Activation('linear'))
model.compile(loss='mse',optimizer='adam')
return model
df = pd.read_csv('Date.csv',usecols=['Date'])
scaler_minmax = MinMaxScaler()
data = scaler_minmax.fit_transform(df)
infer_seq_length = 10#用于推断的历史序列长度
d = []
for i in range(data.shape[0]-infer_seq_length):
d.append(data[i:i+infer_seq_length+1].tolist())
d = np.array(d)
split_rate = 0.9
X_train, y_train = d[:int(d.shape[0]*split_rate),:-1], d[:int(d.shape[0]*split_rate),-1]
model =create_model()
model.fit(X_train, y_train, batch_size=20,epochs=100,validation_split=0.1)
#inverse_transform获得归一化前的原始数据
plt.plot(scaler_minmax.inverse_transform(d[:,-1]),label='true data')
plt.plot(scaler_minmax.inverse_transform(model.predict(d[:,:-1])),'r:',label='predict')
plt.legend()
训练后绘图直观比较真实值和预测值
更多推荐




所有评论(0)