Coursera Big Data系列課程筆記1

hadoop Cloudera virtual machine 操作

http://github.com/words-sdsc/coursera
big-data-1:安裝方式在Introduction to big data課程第一週
big-data-2:安裝方式在Big Data Modeling and Management課程第一週
big-data-3:安裝方式在Big Data Integration and Processing課程第一週

安裝big-data-3等各種工具包

打開 terminal shell window
cd big-data-3
./setup.sh
中間不斷的enter/yes
最後source /home/cloudera/.bashrc

week1 文件操作

cd Downloads   ##將工作區轉移到downloads文件夾 
ls   ##顯示工作區的文件
unzip -o xxx.zip   ##解壓縮文件xxx
./setup.sh   ##安裝setup.sh
q   ##退出more。。

week2 嘗試HDFS並行計算

hadoop fs –copyFromLocal words.txt   ##把文件複製到HDFS
hadoop fs –ls   ##顯示HDFS中的文件
hadoop fs -cp words.txt words2.txt   ##在HDFS裏複製words到words2
hadoop fs -copyToLocal words2.txt   ##把HDFS裏的words2複製到本地
hadoop fs -rm words2.txt   ##從HDFS裏移除words2
hadoop jar /usr/jars/hadoop-examples.jar   ##查看several example MapReduce applications
hadoop jar /usr/jars/hadoop-examples.jar wordcount   ##瞭解示例功能用途
hadoop jar /usr/jars/hadoop-examples.jar wordcount words.txt out   ##啓用wordcount對words.txt進行計算(需要相關文件在HDFS中),並將結果記錄在out文件夾中
hadoop –fs ls out   ##查看out文件夾中的輸出結果
hadoop fs –copyToLocal out/part-r-00000 local.txt
more local.txt   ##查看loca文件內容

oocalc   ##打開oocalc工作表軟件(類似excel)

week3 查看各類數據

cd Downloads/big-data-2/image ##移動至圖片所在文件夾
eog Australia.jpg ##展示圖片 Eye of Gnome is a common image viewer on Linux systems.
./dimensions.py Australia.jpg ##查看圖片大小
./pixel.py Australia.jpg 5000 0 ##查看圖片位置(5000,0)的RGB值

cd Downloads/big-data-2/sensor ##移動至senor數據所在文件夾
more wx-data.txt
more wxt-520-format.txt
./plot-data.py wx-data.txt Ta ##對wx-data數據Ta列繪製折線圖

cd Downloads/big-data-2/json ##移動至json數據所在文件夾
more twitter.json
./json_schema.py twitter.json | more ##查看JSON file概要
./print_json.py ##查看指定內容
    twitter.json ##輸入查看文件
    99 ##輸入查看對象
    text ##輸入查看屬性
    entities/hashtags ##輸入查看屬性

week4 Import and query text documents with Lucene(使用Lucene輸入和分析文本)

ls data/ ##顯示data文件夾下子文件

./runLuceneQuery.sh data   ##導入data文件夾下數據,開始分析數據
    delegates #這時輸入任意單詞,系統顯示相關性
    voters^5 delegates #還可以輸入任意單詞的權重組合,系統會顯示data文件夾下各數據表對該組合的評分

./runLuceneTFIDF.sh data   ##導入data文件夾下數據,開始TF-IDF分析數據
    voters  #data文件夾下各數據表對該單詞的評分【單詞在某數據表出現數/出現總數*log2(數據表數/單詞出現數)

week5 Perform statistical operations and layout algorithms on graph data in Gephi(用Gephi進行網絡分析)

數據源:https://raw.githubusercontent.com/words-sdsc/coursera/master/big-data-2/graph/diseaseGraph.csv
軟件下載: https://gephi.org/users/install

week6 讀取和圖表顯示實時數據流

cd Downloads/big-data-2/sensor
ls
./stream-data.py  ##觀察來自weather station的數據流
./stream-plot-data.py Sm  ##繪製風速平均值動態折線圖
./stream-plot-data.py Ta
ctrl+c ##退出process

week7 讀取和顯示twitter實時數據流

cd Downloads/big-data-2/json
ls
./LiveTweets.py president   ##實時顯示含president的推特數據
./LiveTweets.py time
./PlotTweets.py president   ##繪製含president的推特數據發生頻率

week8 jupyter/psql

pyspark ##啓動pyspark
psql ##啓動Postgres shell數據庫
\d ##顯示數據庫表名單
\d butclicks ##顯示butclicks表信息
select * from buyclicks; ##輸入查詢語句,顯示查詢信息
select price, userid from buyclicks;
select price, userid from buyclicks where price > 10;
select avg(price) from buyclicks;
select sum(price) from buyclicks;
select adid, buyid, adclicks.userid from adclicks join buyclicks on adclicks.userid = buyclicks.userid;

week9 mongodb

cd Downloads/big-data-3/mongodb ##進入mongo文件夾
./mongodb/bin/mongod --dbpath db ##啓動服務器監控(指定服務器地址,顯示服務器信息)

打開一個新terminal shell window窗口

cd Downloads/big-data-3/mongodb

./mongodb/bin/mongo  ##啓動服務器作業shell
show dbs  ##顯示各數據庫
use sample  ##定位sample數據庫
show collections  ##顯示數據表
db.users.count()  ##顯示users數據表記錄總數
db.users.findOne()   ##任意顯示一條users數據表記錄 
db.users.distinct("user_name")  ##顯示去重後的user_name字段信息
db.users.find({user_name:"ActionSportsJax"})  ##查詢user_name是ActionSportsJax的記錄信息
db.users.find({user_name:"ActionSportsJax"}).pretty()   ##按格式顯示上步的信息
db.users.find({user_name:"ActionSportsJax"},{tweet_ID:1}).pretty()   ##只顯示tweet_ID字段
db.users.find({user_name:"ActionSportsJax"},{tweet_ID:1,_id:0}).pretty()   ##去除默認的id字段顯示
db.users.find({tweet_text:"FIFA"})   ##查找tweet_text等於FIFA的記錄
db.users.find({tweet_text:/FIFA/})   ##查找tweet_text含FIFA的記錄(模糊查詢)
db.users.find({tweet_text:/FIFA/}).count
db.users.createIndex({"tweet_text":"text"})  ##在tweet_text字段上建立一個叫text的索引
db.users.find({text:{$search:"FIFA"}}).count()   ##通過索引text查找含FIFA的數量
db.users.find({text:{$search:"FIFA -Texas"}}).count()   ##通過索引text查找含FIFA不含Texas的數量
db.users.find({tweet_mentioned_count:{$gt:6}})  ##查找tweet_mentioned_count大於6的記錄
db.users.find({$where:"this.tweet_mentioned_count > this.tweet_followers_count"}).count()  
    ##查找tweet_mentioned_count字段大於tweet_followers_count字段的記錄數量,注意需要加上this.代表當前文檔
db.users.find({$and:[{tweet_text:"FIFA"},{tweet_mentioned_count:{$gt:4}}]}).count()
    ##查找既滿足xxx又滿足xx的記錄數量
exit ##關閉服務器作業shell
Control-C  ##關閉服務器監控(在第一次打開的terminal shell window)

week9 Pandas DataFrames

pyspark ##啓動pyspark
在打開的瀏覽器中找到Download,big-data-3
右上角New,用python3創建一個新的Notebooks
##這裏我理解相當於在通過瀏覽器中編寫python3腳本
##編寫好後,按shift+enter,run腳本

[1] import pandas  ##啓用pandas包
[2] buyclicksDF=pandas.read_csv('buy-clicks.csv')  ##讀取工作目錄下csv文件
[3] buyclicksDF  ##顯示結果
[4] buyclicksDF.head(5)  ##顯示前5行
[5] buyclicksDF.shape  ##表的行列數
[6] buyclicksDF[['price','userId']].head(5)  ##顯示price、userid兩列
[7] buyclicksDF[buyclicksDF['price']<3].head(5)  ##顯示price<3的數據
[8] buyclicksDF['price'].mean()
[9] buyclicksDF['price'].sum()

更多操作介紹
http://pandas.pydata.org/pandas-docs/stable/api.html#computations-descriptive-stats

[10] mergeDF = adclicksDF.merge(buyclicksDF,on='userID')  ##通過userid字段合併adclicksDF和buyclicksDF兩表

week10 splunk and datameer

這兩個軟件都可以將各種類型的數據,包括實時網絡數據、html數據、靜態數據、感應器數據等,按一定的條件轉換爲具體的數據、圖表和數據挖掘模型,都可基於hadoop的框架下進行操作。
splunk下載地址:https://www.splunk.com/en_us/download/splunk-enterprise.html?ac=coursera_download
啓動網站:http://localhost:8000

搜索:

STNAME="California" CENSUS2010POP>1000000 
STNAME="California" CENSUS2010POP>1000000 | table CTYNAME
CENSUS2010POP>1000000 | sort CENSUS2010POP desc |table CENSUS2010POP,CTYNAME
STNAME="California" CENSUS2010POP>1000000 | table CTYNAME,CENSUS2010POP
STNAME="California"  | stats count 
STNAME="California"  | stats sum(CENSUS2010POP)

week11 wordcount-in-spark

hadoop fs -ls ##顯示hdfs系統中的文檔
pyspark #啓動網頁窗口
在打開的瀏覽器中找到Downloads/big-data-3
右上角New,用python3創建一個新的Notebooks

編寫好後,按shift+enter,run腳本

from pyspark.sql import SQLContext
sqlContext=SQLContext(sc)
[1] lines=sc.textFile("hdfs:/user/coludera/words.txt")  ##將hdfs系統中的文檔讀取到spark RDD系統中
[2] lines.count  ##查看行數
[3] words=lines.flatMap(lambda line : line.split(" "))  ##flatMap是按照括號裏的func生成1對多的結果;這邊將各行分解爲單詞
[4] words.take(5)  ##顯示words前5個值
['This','is','the','100th','Etext']
[5] tuples=words.map(lambda word :(word,1))  ##map是按照括號裏的func生成1對1的結果;這邊是生成一個數組
[6] tuples.take(5)  ##顯示前5個值
[('This',1),('is',1),('the',1),('100th',1),('Etext',1)]
[7] counts=tuples.reduceByKey(lambda a,b:(a+b))  ##reduceByKey是按照括號裏的fun按key值合併數組
[8] counts.take(5)  ##顯示前5個值
[('',517065),('VENTIDIUS',3),('Stockfish,',1),('Corin,',2),('Begin',6)]
[9] counts.coalesce(1).saveAsTextFile('hdfs:/user/cloudera/wordcount/outputDir') ##coalesce將多個部分的計算結果合併爲一個;這邊將計算結果保存到hdfs系統中

week12 SparkSQL and Spark DataFrame

pyspark #啓動網頁窗口
在打開的瀏覽器中找到Downloads/big-data-3/spark-sql
點擊SparkSQL.ipynb

[1] form pyspark.sql import SQLContext  ##加載SQLContext
[2] sqlsc=SQLContext(sc)    ##創建一個SQLContext          
[3] df =sqlsc.read.format("jdbc") \
   .option("url","jdbc:postgresql://localhost/cloudera?user=cloudera") \
   .option("dbtable","gameclicks") \
   .load()    ##按java數據結構讀取指定連接指定表的數據
[4] df.printSchema()  ##顯示錶結構
[5] df.count()   ##顯示錶行數
[6] df.show(5)   ##顯示前5行
[7] df.select("userid","teamlevel").show(5)   ##顯示userid、teamlevel字段前5行
[8] df.filter(df["teamlevel"]>1).select("userid","teamlevel").show(5)   ##顯示teamlevel大於1的前5行
[9] df.groupBy("ishit").count().show()   ##顯示分組合計結果
[10] from pyspark.sql.functions import *   ##加載aggregate
     df.select(mean('ishit'),sum("ishit")).show()   ##查看錶ishit字段的平均值和合計
[11] df2=sqlsc.read.format("jdbc") \  
   .option("url","jdbc:postgresql://localhost/cloudera?user=cloudera") \
   .option("dbtable","adclicks") \
   .load()   ##讀取另一張表
[12] df2.printSchema()
[13] merge =df.join(df2,'userid')   ##通過userid字段將兩表合併起來
[14] merge.printSchema()   ##查看合併結果結構
[15] merge.show(5)

week13 Spark Streaming

因爲Spark Streaming需要2個以上的處理器,所以,分配需要通過虛擬機設置分配2個以上處理器。
pyspark #啓動網頁窗口
在打開的瀏覽器中找到Downloads/big-data-3/spark-sql
點擊Spark-Streaming.ipynb

[1] import re
    def parse(line):
        match =re.search("Dm=(\d+)",line)
    if match:
         val=match.group(1)
             return [int(val)]
    return []            ##創建一個函數parse返回Dm值
[2] from pyspark.streaming import StreamingContext
    ssc = StreamingContext(sc,1)  ##加載並創建一個新的StreamingContext(SparkContext,間隔1s)     
[3] lines=ssc.socketTextStream("rtd.hpwren.edu",12028)  ##建立連接流數據
[4] vals=lines.flatMap(parse) ##將對lines的計算結果儲存在新的DStream對象中
[5] window=vals.window(10,5)  ##創建一個長度爲10s,每次移動5s的滑窗
[6] def stats(rdd):
    print(rdd.collect())
    if rdd.count()>0:
        print("max={},min={}".format(rdd.max(),rdd.min())  
    ##創意一個函數,顯示整個rdd的值,顯示rdd的最大值、最小值
[7] window.foreachRDD(lambda rdd:stats(rdd))  ##對每個滑窗範圍內的RDD使用stats函數
[8] ssc.start()   ##顯示結果

這裏寫圖片描述

[9] ssc.stop()   ##關閉d

week14 mongodb test

cd Downloads/big-data-3/mongodb ##進入mongo文件夾
./mongodb/bin/mongod --dbpath db ##啓動服務器監控(指定服務器地址,顯示服務器信息)

打開一個新terminal shell window窗口

cd Downloads/big-data-3/mongodb

./mongodb/bin/mongo  ##啓動服務器作業shell
show dbs  ##顯示各數據庫
use sample  ##定位sample數據庫
show collections  ##顯示數據表
db.users.find({"user.Location":null}).count()  ##查看user下Location值爲null的
db.users.find({"user.Location":{$ne:null}}).count()  ##查看user下Location值不爲null
db.users.find({$where:"this.user.FollowersCount>this.user.FriendsCount"}).count()   ##查看follow人數多於好友人數的
db.users.find({tweet_text:/http\:\/\//}).pretty()  ##查找推特內容包含http://的
db.users.find({$and:[{tweet_text:{$not:/UEFA/}},{tweet_text:/England/},{tweet_text:/Euro 2016/}]}).count()   ##查找推特內容不包含UEFA,包含England和Euro 2016的
db.users.find({$and:[(tweet_text:/UEFA/},{"user.Location":"Ireland}]}).pretty()   ##查找推特內容包含UEFA,用戶所在地在Ireland的

week14 mongodb test2

cd Downloads/big-data-3/mongodb ##進入mongo文件夾
./mongodb/bin/mongod --dbpath db ##啓動服務器監控(指定服務器地址,顯示服務器信息)

打開一個新terminal shell window窗口

cd Downloads/big-data-3/mongodb

./mongodb/bin/mongoexport -d sample -c users --type=csv -f tweet_text -o itweet  ##導出mongo查詢結果
--collection <name> ##選擇數據表名
--db <name> ##選擇數據庫名
--fields <field 1>,<field 2>,<...>  ##選擇輸出的字段
--query <query> ##查詢語句
--out <name>    ##輸出的表名te
--type=<type>   ##輸出表格式

導出的文件在Downloads/big-data-3/mongodb文件夾中

week15 spark test

pyspark #啓動網頁窗口

[1] from pyspark.sql import SQLContext ##加載SQLContext
    sqlContext=SQLContext(sc)     ##創建一個SQLContext    
[2] country_lines=sc.textFile('file:///home/cloudera/Downloads/big-data-3/final-project/country-list.csv')  ##讀取國家信息csv到RDD中
[3] country_tuples=country_lines.map(lambda line:line.split(", ")))  ##將每一行拆分爲一個數組
    country_tuples.take(5)  
[4] countryDF=sqlContext.createDataFrame(country_tuples,["country","code"])  ##將country_tuples轉換爲一個dataframe
        countryDF=printSchema()  ##dataframe的結構
        countryDF.takes=(3)
[5] tweet_lines= sc.textFile('file:///home/cloudera/Downloads/big-data-3/mongodb/itweet')  ##讀取tweet數據
[6] tweet_words=tweet_lines.flatMap(lambda line:line.split(" "))  #將每一行拆分爲各個單詞
    tweet_words.take(5)
[7] tweet_tuples=tweet_words.map(lambda word:(word,1))
    tweet_tuples.take(5)
    tweet.counts=tweet_tuples.reduceByKey(lambda a,b:(a+b))
[8] tweetDF=sqlContext.createDataFrame(tweet_counts,["words","counts"]) ##把tweet也轉換爲一個dataframe
    tweetDF.printSchema()
    tweetDF.take(3)
[9] merge=countryDF.join(tweetDF,countryDF.country==tweetDF.words)  ##按照關鍵詞(countryDF表中country,tweetDF表中的words)合併倆個dataframe,得到每個國家在推特中被提到了幾次
[10] merge.count() ##總共被提到的國家數
[11] from pyspark.sql.functions import sum
    merge.select(sum('counts')).show()  ##被推特提到的國家合計次數
[12] from pyspark.sql.functions import desc
    merge.sort(desc('counts')).show(3)  ##顯示被推特提到最多次的國家
[13] merge.filter("country='Wales' OR country='Iceland'").show()  ##顯示Wales和Iceland兩個國家被提到的次數
[14] from pyspark.sql.functions import mean
    merge.select(mean('counts')).show()  ##顯示各國平均被提到的次數

week16 KNIME

基於Eclipse環境的開源商業智能工具。KNIME是通過工作流來控制數據的集成、清洗、轉換、過濾,再到統計、數據挖掘,最後是數據的可視化。整個開發都在可視化的環境下進行,通過簡單的拖曳和設置就可以完成一個流程的開發

下載地址:
https://www.knime.org/downloads/overview?quicktabs_knimed=1#quicktabs-knimed
KNIME Website
KNIME Getting Started
KNIME Online Self-Training
KNIME Quickstart Guide
KNIME Node Documentation
KNIME Learning Hub
KNIME Community
KNIME Labs

week17 spark data exploration

pyspark #啓動網頁窗口

[1] from pyspark.sql import SQLContext ##加載SQLContext
    sqlContext=SQLContext(sc)     ##創建一個SQLContext    
[2] df=sqlContext.read.load('file:///home/cloudera/Downloads/big-data-4/daily_weather.csv',
    format='com.databricks.spark.csv',
    header='true',inferSchema='true') ##讀取天氣數據到數據框中
[3] df.columns  ##顯示數據框列頭
[4] df.printSchema() ##顯示數據框列信息
[5] df.describe().toPandas().transpose()  ##顯示數據框描述性統計信息
[6] df.describe('air_pressure_9am').show()  ##顯示數據框某列描述性統計信息
[7] len(df.columns) ##顯示列數
[8] df.count() ##顯示行數
[9] df2=df.na.drop(subset=['air_pressure_9am']) ##去除某列字段缺失數據行
[10] df2.count()
[11] df2.stat.corr("rain_accumulation_9am","rain_duration_9am") ##a列與b列計算相關係數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章