markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Do you see the "elbow"? At what value of $k$ does it occur? Evaluate the results of our clustering algorithm for the best $k$ Use the slider below to choose the "best" $k$ that you determined from looking at the elbow plot. Evaluate the results in the PCA plot. Does this look like a good value of $k$ to separate the d... | best_k = 1 #@param {type:"slider", min:1, max:10, step:1}
# Cluster the data using the k means algorithm
best_cluster_results = KMeans(n_clusters=best_k, n_init=25, random_state=rs).fit(scaled_df)
# Save the cluster labels in our dataframe
tracks_df['best_cluster'] = ['Cluster ' + str(i) for i in best_cluster_results... | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
How did we do? In addition to the mathematical ways to validate the selection of the best $k$ parameter for our model and the quality of our resulting clusters, there's another very important way to evaluate our results: listening to the tracks!Let's listen to the tracks in each cluster! What do you notice about the a... | play_cluster_tracks(tracks_df, cluster_column='best_cluster') | Cluster 0
Track Name: Needy Bees
Artist Name(s): Nick Hakim
| MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Python是什么? Python是一种高级的多用途编程语言,广泛用于各种非技术和技术领域。Python是一种具备动态语义、面向对象的解释型高级编程语言。它的高级内建数据结构和动态类型及动态绑定相结合,使其在快速应用开发上极具吸引力,也适合于作为脚本或者“粘合剂”语言,将现有组件连接起来。Python简单、易学的语法强调可读性,因此可以降低程序维护成本。Python支持模块和软件包,鼓励模块化的代码重用。 | print('hellow world') | hellow world
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python简史 1989,为了度过圣诞假期,Guido开始编写Python语言编译器。Python这个名字来自Guido的喜爱的电视连续剧《蒙蒂蟒蛇的飞行马戏团》。他希望新的语言Python能够满足他在C和Shell之间创建全功能、易学、可扩展的语言的愿景。 1989年由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年 Granddaddy of Python web frameworks, Zope 1 was released in 1999 Python 1.0 - January 1994 增加了 lambda, map, filter and reduce. Python 2.0... | import math
print(math.pi)
print(math.log(1024, 2)) | 3.141592653589793
10.0
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
random提供了生成随机数的工具。 | import random
print(random.choice(['apple', 'pear', 'banana']))
print(random.random()) | apple
0.0034954793658343863
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
datetime模块为日期和时间处理同时提供了简单和复杂的方法。 | from datetime import date
now = date.today()
birthday = date(1999, 8, 20)
age = now - birthday
print(age.days) | 7625
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Numpy是高性能科学计算和数据分析的基础包。 Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。 Statismodels是一个Python模块,它提供对许多不同统计模型估计的类和函数,并且可以进行统计测试和统计数据的探索。 matplotlib一个绘制数据图的库。对于数据科学家或分析师非常有用。 更多https://docs.python.org/zh-cn/3/library/ 基础架构工具 Anaconda安装 https://www.anaconda.com/products/individual Spyder使用 GitHub创建与使用 GitHub 是一个面向开源及私有软... | print ("Hello, Python!") | Hello, Python!
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
行和缩进 python 最具特色的就是用缩进来写模块。 缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。 以下实例缩进为四个空格: | if 1>2:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
# 没有严格缩进,在执行时会报错
print ("False") | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
多行语句 Python语句中一般以新行作为语句的结束符。 但是我们可以使用斜杠( \)将一行的语句分为多行显示,如下所示: | total = 1 + \
2 + \
3
print(total) | 6
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
语句中包含 [], {} 或 () 括号就不需要使用多行连接符。如下实例: | days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
print(days) | ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python 引号 Python 可以使用引号( ' )、双引号( " )、三引号( ''' 或 """ ) 来表示字符串,引号的开始与结束必须是相同类型的。 其中三引号可以由多行组成,编写多行文本的快捷语法,常用于文档字符串,在文件的特定地点,被当做注释。 | word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""
print(word)
print(sentence)
print(paragraph) | word
这是一个句子。
这是一个段落。
包含了多个语句
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python注释 python中单行注释采用 开头。 | # 第一个注释
print ("Hello, Python!") # 第二个注释 | Hello, Python!
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python变量类型 标准数据类型 在内存中存储的数据可以有多种类型。 例如,一个人的年龄可以用数字来存储,他的名字可以用字符来存储。 Python 定义了一些标准类型,用于存储各种类型的数据。 Python有五个标准的数据类型: Numbers(数字) String(字符串) List(列表) Tuple(元组) Dictionary(字典) Python数字 Python支持三种不同的数字类型: int(有符号整型) float(浮点型) complex(复数) | int1 = 1
float2 = 2.0
complex3 = 1+2j
print(type(int1),type(float2),type(complex3)) | <class 'int'> <class 'float'> <class 'complex'>
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python字符串 字符串或串(String)是由数字、字母、下划线组成的一串字符。 | st = '123asd_'
st1 = st[0:3]
print(st)
print(st1) | 123asd_
123
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python列表 List(列表) 是 Python 中使用最频繁的数据类型。 列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。 列表用 [ ] 标识,是 python 最通用的复合数据类型。 | list1 = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list1) # 输出完整列表
print (list1[0]) # 输出列表的第一个元素
print (list1[1:3]) # 输出第二个至第三个元素
print (list1[2:]) # 输出从第三个开始至列表末尾的所有元素
print (tinylist * 2) # 输出列表两次
print (list1 + tinylist) # 打印组... | ['runoob', 786, 2.23, 'john', 70.2]
runoob
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['runoob', 786, 2.23, 'john', 70.2, 123, 'john']
[0, 786, 2.23, 'john', 70.2]
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python元组 元组是另一个数据类型,类似于 List(列表)。 元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。 | tuple1 = ( 'runoob', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print(tuple1[0])
print(tuple1+tinytuple) | runoob
('runoob', 786, 2.23, 'john', 70.2, 123, 'john')
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python 字典 字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象集合,字典是无序的对象集合。 两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 字典用"{ }"标识。字典由索引(key)和它对应的值value组成。 | dict1 = {}
dict1['one'] = "This is one"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print(tinydict['name'])
print(dict1)
print(tinydict.keys())
print(tinydict.values()) | john
{'one': 'This is one'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python运算符 Python算术运算符 | a = 21
b = 10
c = 0
c = a + b
print ("c 的值为:", c)
c = a - b
print ("c 的值为:", c)
c = a * b
print ("c 的值为:", c)
c = a / b
print ("c 的值为:", c)
c = a % b #取余数
print ("c 的值为:", c)
# 修改变量 a 、b 、c
a = 2
b = 3
c = a**b
print ("c 的值为:", c)
a = 10
b = 5
c = a//b #取整
print ("c 的值为:", c) | c 的值为: 31
c 的值为: 11
c 的值为: 210
c 的值为: 2.1
c 的值为: 1
c 的值为: 8
c 的值为: 2
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python比较运算符 | a = 21
b = 10
c = 0
if a == b :
print ("a 等于 b")
else:
print ("a 不等于 b")
if a != b :
print ("a 不等于 b")
else:
print ("a 等于 b")
if a < b :
print ("a 小于 b")
else:
print ("a 大于等于 b")
if a > b :
print ("a 大于 b")
else:
print ("a 小于等于 b")
# 修改变量 a 和 b 的值
a = 5
b = 20
if a <= b :
... | a 不等于 b
a 不等于 b
a 大于等于 b
a 大于 b
a 小于等于 b
b 大于等于 a
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python逻辑运算符 | a = True
b = False
if a and b :
print ("变量 a 和 b 都为 true")
else:
print ("变量 a 和 b 有一个不为 true")
if a or b :
print ("变量 a 和 b 都为 true,或其中一个变量为 true")
else:
print ("变量 a 和 b 都不为 true")
if not( a and b ):
print ("变量 a 和 b 都为 false,或其中一个变量为 false")
else:
print ("变量 a 和 b 都为 true") | 变量 a 和 b 有一个不为 true
变量 a 和 b 都为 true,或其中一个变量为 true
变量 a 和 b 都为 false,或其中一个变量为 false
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python赋值运算符 | a = 21
b = 10
c = 0
c = a + b
print ("c 的值为:", c)
c += a
print ("c 的值为:", c)
c *= a
print ("c 的值为:", c)
c /= a
print ("c 的值为:", c)
c = 2
c %= a
print ("c 的值为:", c)
c **= a
print ("c 的值为:", c)
c //= a
print ("c 的值为:", c) | c 的值为: 31
c 的值为: 52
c 的值为: 1092
c 的值为: 52.0
c 的值为: 2
c 的值为: 2097152
c 的值为: 99864
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python 条件语句 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。 | flag = False
name = 'luren'
if name == 'python': # 判断变量是否为 python
flag = True # 条件成立时设置标志为真
print ('welcome boss') # 并输出欢迎信息
else:
print (name) # 条件不成立时输出变量名称
num = 5
if num == 3: # 判断num的值
print ('boss')
elif num == 2:
print ('user... | hello
undefine
undefine
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python循环语句 Python 提供了 for 循环和 while 循环 Python While 循环语句 Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。 | count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5") | 0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python for 循环语句 | fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('当前水果 :', fruits[index])
print ("Good bye!") | 当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python 循环嵌套 | num=[];
i=2
for i in range(2,100):
j=2
for j in range(2,i):
if(i%j==0):
break
else:
num.append(i)
print(num)
print ("Good bye!") | [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Good bye!
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python break 语句 | for letter in 'Python':
if letter == 'h':
break
print ('当前字母 :', letter) | 当前字母 : P
当前字母 : y
当前字母 : t
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python continue 语句 Python continue 语句跳出本次循环,而break跳出整个循环。 | for letter in 'Python':
if letter == 'h':
continue
print ('当前字母 :', letter) | 当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python pass 语句 Python pass 是空语句,是为了保持程序结构的完整性。 pass 不做任何事情,一般用做占位语句。 | # 输出 Python 的每个字母
for letter in 'Python':
if letter == 'h':
pass
print ('这是 pass 块')
print ('当前字母 :', letter)
print ("Good bye!") | 当前字母 : P
当前字母 : y
当前字母 : t
这是 pass 块
当前字母 : h
当前字母 : o
当前字母 : n
Good bye!
| MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Python应用实例(链家二手房数据分析) 一、根据上海的部分二手房信息,从多角度进行观察和分析房价与哪些因素有关以及房屋不同状况所占比例 二、先对数据进行预处理、构造预测房价的模型、并输入参数对房价进行预测备注:数据来源CSDN下载。上海链家二手房.csv.因文件读入问题,改名为sh.csv 一、导入数据 对数据进行一些简单的预处理 | #导入需要用到的包
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
from IPython.display import display
sns.set_style({'font.sans-serif':['simhei','Arial']})
%matplotlib inline
shanghai=pd.read_csv('sh.csv')# 将已有数据导进来
shanghai.head(n=1)#显示第一行数据 查看数据是否导入成功 | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
每项数据类型均为object 不方便处理,需要对一些项删除单位转换为int或者float类型 有些列冗余 像house_img需要删除 有些列 如何house_desc包含多种信息 需要逐个提出来单独处理 | shanghai.describe()
# 检查缺失值情况
shanghai.info()
#np.isnan(shanghai).any()
shanghai.dropna(inplace=True)
#数据处理 删除带有NAN项的行
df=shanghai.copy()
house_desc=df['house_desc']
house_desc[0] | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
house_desc 中带有 室厅的信息 房子面积 楼层 朝向信息 需要分别提出来当一列 下面进行提取 | df['layout']=df['house_desc'].map(lambda x:x.split('|')[0])
df['area']=df['house_desc'].map(lambda x:x.split('|')[1])
df['temp']=df['house_desc'].map(lambda x:x.split('|')[2])
#df['Dirextion']=df['house_desc'].map(lambda x:x.split('|')[3])
df['floor']=df['temp'].map(lambda x:x.split('/')[0])
df.head(n=1) | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
一些列中带有单位 不利于后期处理 去掉单位 并把数据类型转换为float或int | df['area']=df['area'].apply(lambda x:x.rstrip('平'))
df['singel_price']=df['singel_price'].apply(lambda x:x.rstrip('元/平'))
df['singel_price']=df['singel_price'].apply(lambda x:x.lstrip('单价'))
df['district']=df['district'].apply(lambda x:x.rstrip('二手房'))
df['house_time']=df['house_time'].apply(lambda x:str(x))
df['house_... | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
删除一些不需要用到的列 以及 house_desc、temp | del df['house_img']
del df['s_cate_href']
del df['house_desc']
del df['zone_href']
del df['house_href']
del df['temp'] | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
根据房子总价和房子面积 计算房子每平方米的价格 从house_title 描述房子信息中提取关键词。若带有 交通便利、地铁则认为其交通方便,否则交通不便 | df.head(n=1)
df['singel_price']=df['singel_price'].apply(lambda x:float(x))
df['area']=df['area'].apply(lambda x:float(x))
df.head(n=1)
df.head(n=1)
df['house_title']=df['house_title'].apply(lambda x:str(x))
df['trafic']=df['house_title'].apply(lambda x:'交通便利' if x.find("交通便利")>=0 or x.find("地铁")>=0 else "交通不便" )
df.h... | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
二、根据各列信息 用可视化的形式展现 房价与不同因素如地区、房子面积、所在楼层等之间的关系 | df_house_count = df.groupby('district')['house_price'].count().sort_values(ascending=False).to_frame().reset_index()
df_house_mean = df.groupby('district')['singel_price'].mean().sort_values(ascending=False).to_frame().reset_index()
f, [ax1,ax2,ax3] = plt.subplots(3,1,figsize=(20,15))
sns.barplot(x='district', y='sing... | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
上面三幅图显示了 房子单价、总数量、总价与地区之间的关系。 由上面第一幅图可以看到房子单价与地区有关,其中黄浦以及静安地区房价最高。这与地区的发展水平、交通便利程度以及离市中心远近程度有关 由上面第二幅图可以直接看出不同地区的二手房数量,其中浦东最多 由上面第三幅图可以看出上海二手房房价基本在一千万上下,很少有高于两千万的 | f, [ax1,ax2] = plt.subplots(1, 2, figsize=(15, 5))
# 二手房的面积分布
sns.distplot(df['area'], bins=20, ax=ax1, color='r')
sns.kdeplot(df['area'], shade=True, ax=ax1)
# 二手房面积和价位的关系
sns.regplot(x='area', y='house_price', data=df, ax=ax2)
plt.show() | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
由从左到右第一幅图可以看出 基本二手房面积在60-200平方米之间,其中一百平方米左右的占比更大 由第二幅看出,二手房总结与二手房面积基本成正比,和我们的常识吻合 | areas=[len(df[df.area<100]),len(df[(df.area>100)&(df.area<200)]),len(df[df.area>200])]
labels=['area<100' , '100<area<200','area>200']
plt.pie(areas,labels= labels,autopct='%0f%%',shadow=True)
plt.show()
# 绘制饼图 | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
将面积划分为三个档次,面积大于200、面积小与100、面积在一百到两百之间 三者的占比情况可以发现 百分之六十九的房子面积在一百平方米一下,高于一百大于200的只有百分之二十五而面积大于两百的只有百分之四 | df.loc[df['area']>1000]
# 查看size>1000的样本 发现只有一个是大于1000
f, ax1= plt.subplots(figsize=(20,20))
sns.countplot(y='layout', data=df, ax=ax1)
ax1.set_title('房屋户型',fontsize=15)
ax1.set_xlabel('数量')
ax1.set_ylabel('户型')
f, ax2= plt.subplots(figsize=(20,20))
sns.barplot(y='layout', x='house_price', data=df, ax=ax2)
plt.show() | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
上述两幅图显示了 不同户型的数量和价格 由第一幅图看出2室1厅最多 2室2厅 3室2厅也较多 是主流的户型选择 由第二幅看出 室和厅的数量增加随之价格也增加,但是室和厅之间的比例要适合 | a1=0
a2=0
for x in df['trafic']:
if x=='交通便利':
a1=a1+1
else:
a2=a2+1
sizes=[a1,a2]
labels=['交通便利' , '交通不便']
plt.pie(sizes,labels= labels,autopct='%0f%%',shadow=True)
plt.show() | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
上述图显示了上海二手房交通不便利情况。其中百分之六十一为交通不便,百分之三十八为交通不便。由于交通便利情况仅仅是根据对房屋的描述情况提取出来的,实际上 交通便利的占比会更高些 | f, [ax1,ax2] = plt.subplots(1, 2, figsize=(20, 10))
sns.countplot(df['trafic'], ax=ax1)
ax1.set_title('交通是否便利数量对比',fontsize=15)
ax1.set_xlabel('交通是否便利')
ax1.set_ylabel('数量')
sns.barplot(x='trafic', y='house_price', data=df, ax=ax2)
ax2.set_title('交通是否便利房价对比',fontsize=15)
ax2.set_xlabel('交通是否便利')
ax2.set_ylabel('总价')
p... | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
左边那幅图显示了交通便利以及不便的二手房数量,这与我们刚才的饼图信息一致 右边那幅图显示了交通便利与否与房价的关系。交通便利的房子价格更高 | f, ax1= plt.subplots(figsize=(20,5))
sns.countplot(x='floor', data=df, ax=ax1)
ax1.set_title('楼层',fontsize=15)
ax1.set_xlabel('楼层数')
ax1.set_ylabel('数量')
f, ax2 = plt.subplots(figsize=(20, 5))
sns.barplot(x='floor', y='house_price', data=df, ax=ax2)
ax2.set_title('楼层',fontsize=15)
ax2.set_xlabel('楼层数')
ax2.set_ylabel('... | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
楼层(地区、高区、中区、地下几层)与数量、房价的关系。高区、中区、低区居多 三、根据已有数据建立简单的上海二手房房间预测模型 对数据再次进行简单的预处理 把户型这列拆成室和厅 | df[['室','厅']] = df['layout'].str.extract(r'(\d+)室(\d+)厅')
df['室'] = df['室'].astype(float)
df['厅'] = df['厅'].astype(float)
del df['layout']
df.head()
df.dropna(inplace=True)
df.info()
df.columns | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
删除不需要用到的信息如房子的基本信息描述 | del df['house_title']
del df['house_detail']
del df['s_cate']
from sklearn.linear_model import LinearRegression
linear = LinearRegression()
area=df['area']
price=df['house_price']
area = np.array(area).reshape(-1,1) # 这里需要注意新版的sklearn需要将数据转换为矩阵才能进行计算
price = np.array(price).reshape(-1,1)
# 训练模型
model = linear.fit(area,... | _____no_output_____ | MIT | topic1_introduction_of_Python/Part1_Python_Introduction.ipynb | AbnerCui/Python_Lectures |
Exercise: electrical cars | # Imports:
import requests
from bs4 import BeautifulSoup
import re
import time
headers = {'user-agent': 'scrapingCourseBot'}
# Retrieve the number of electrical Renaults built between 2010 and 2014 and
# print the tag containing the number of occasions:
pars = {'bmin': 2010, 'bmax': 2014}
r2 = requests.get('https://ww... | _____no_output_____ | CC-BY-4.0 | 20200907/Answers/Electrical_Cars.ipynb | SNStatComp/CBSAcademyBD |
Concise Chit ChatGitHub Repository: Code TODO:1. create a DataLoader class for dataset preprocess. (Use tf.data.Dataset inside?)1. Create a PyPI package for easy load cornell movie curpos dataset(?)1. Use PyPI module `embeddings` to load `GLOVES`, or use tfhub to load `GLOVES`?1. How to do a `clip_norm`(or set `clip... | '''doc'''
# GO for start of the sentence
# DONE for end of the sentence
GO = '\b'
DONE = '\a'
# max words per sentence
MAX_LEN = 20
| _____no_output_____ | Apache-2.0 | Concise_Chit_Chat.ipynb | huan/python-concise-chit-chat |
data_loader.py | '''
data loader
'''
import gzip
import re
from typing import (
# Any,
List,
Tuple,
)
import tensorflow as tf
import numpy as np
# from .config import (
# GO,
# DONE,
# MAX_LEN,
# )
DATASET_URL = 'https://github.com/huan/concise-chit-chat/releases/download/v0.0.1/dataset.txt.gz'
DATASET_FILE_N... | _____no_output_____ | Apache-2.0 | Concise_Chit_Chat.ipynb | huan/python-concise-chit-chat |
vocabulary.py | '''doc'''
import re
from typing import (
List,
)
import tensorflow as tf
# from .config import (
# DONE,
# GO,
# MAX_LEN,
# )
class Vocabulary:
'''voc'''
def __init__(self, text: str) -> None:
self.tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='')
self.tokenizer.f... | _____no_output_____ | Apache-2.0 | Concise_Chit_Chat.ipynb | huan/python-concise-chit-chat |
model.py | '''doc'''
import tensorflow as tf
import numpy as np
from typing import (
List,
)
# from .vocabulary import Vocabulary
# from .config import (
# DONE,
# GO,
# MAX_LENGTH,
# )
EMBEDDING_DIM = 300
LATENT_UNIT_NUM = 500
class ChitEncoder(tf.keras.Model):
'''encoder'''
def __init__(
... | _____no_output_____ | Apache-2.0 | Concise_Chit_Chat.ipynb | huan/python-concise-chit-chat |
Train Tensor Board[Quick guide to run TensorBoard in Google Colab](https://www.dlology.com/blog/quick-guide-to-run-tensorboard-in-google-colab/)`tensorboard` vs `tensorboard/` ? |
LOG_DIR = '/content/data/tensorboard/'
get_ipython().system_raw(
'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
.format(LOG_DIR)
)
# Install
! npm install -g localtunnel
# Tunnel port 6006 (TensorBoard assumed running)
get_ipython().system_raw('lt --port 6006 >> url.txt 2>&1 &')
# Get url
! cat url.t... | your url is: https://bright-fox-51.localtunnel.me
| Apache-2.0 | Concise_Chit_Chat.ipynb | huan/python-concise-chit-chat |
chat.py | '''train'''
# import tensorflow as tf
# from chit_chat import (
# ChitChat,
# DataLoader,
# Vocabulary,
# DONE,
# GO,
# )
# tf.enable_eager_execution()
def main() -> int:
'''chat main'''
data_loader = DataLoader()
vocabulary = Vocabulary(data_loader.raw_text)
print('Dataset size... | processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 63
model name : Intel(R) Xeon(R) CPU @ 2.30GHz
stepping : 0
microcode : 0x1
cpu MHz : 2299.998
cache size : 46080 KB
physical id : 0
siblings : 2
core id : 0
cpu cores : 1
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 13
wp ... | Apache-2.0 | Concise_Chit_Chat.ipynb | huan/python-concise-chit-chat |
Scraping de Características Generales Se obtienen características generales del equipo de la página whoscored.Las estadísticas son de la temporada más reciente.  | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import Select
option = webd... | _____no_output_____ | MIT | CaracteristicasPorEquipo.ipynb | Howl24/Lineup-Prediction |
Procesamiento de datos de equipos | %matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("características_equipos.csv")
df['rating'] = df['rating'].apply(lambda x: x.replace(',', '.')).astype(float)
x = range(len(df['rating']))
df = df.sort_values('rating')
plt.barh(x, df['rating'])
plt.yticks(x, df['Equipo']) | _____no_output_____ | MIT | CaracteristicasPorEquipo.ipynb | Howl24/Lineup-Prediction |
Database Load | # Dependencies and Setup
import json
import os
import pandas as pd
import urllib.request
import requests
# from config import db_pwd, db_user
from config import URI
from sqlalchemy import create_engine | _____no_output_____ | MIT | TEST/Database/Database - Project 3.ipynb | LoriWard/COVID-Trends-Website |
Load Data into DataFrame | csv_file = "data/Merged_data.csv"
google_data_df = pd.read_csv(csv_file)
google_data_df.head()
google_df = google_data_df[["states","dates","SMA_retail_recreation", "SMA_grocery_pharmacy", "SMA_parks",
"SMA_transit", "SMA_workplaces", "SMA_residential", "case_count", "new_case_count", "reven... | _____no_output_____ | MIT | TEST/Database/Database - Project 3.ipynb | LoriWard/COVID-Trends-Website |
Check for tables | engine.table_names() | _____no_output_____ | MIT | TEST/Database/Database - Project 3.ipynb | LoriWard/COVID-Trends-Website |
Use pandas to load csv converted DataFrame into database | google_df.to_sql(name='merged_data', con=engine, if_exists='append', index=False) | _____no_output_____ | MIT | TEST/Database/Database - Project 3.ipynb | LoriWard/COVID-Trends-Website |
Confirm data has been added by querying the tables | pd.read_sql_query('select * from merged_data', con=engine).head(10)
pd.read_sql_query('select sma_workplaces from merged_data', con=engine).head(10) | _____no_output_____ | MIT | TEST/Database/Database - Project 3.ipynb | LoriWard/COVID-Trends-Website |
Trusted Notebook" width="500 px" align="left"> _*Quantum K-Means algorithm*_ The latest version of this notebook is available on https://github.com/qiskit/qiskit-tutorial.*** Contributors Shan Jin, Xi He, Xiaokai Hou, Li Sun, Dingding Wen, Shaojun Wu and Xiaoting Wang$^{1}$1. Institute of Fundamental and Frontier Sci... | # import math lib
from math import pi
# import Qiskit
from qiskit import Aer, IBMQ, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# To use local qasm simulator
backend = Aer.get_backend('qasm_simulator') | _____no_output_____ | Apache-2.0 | community/awards/teach_me_qiskit_2018/quantum_machine_learning/1_K_Means/Quantum K-Means Algorithm.ipynb | Chibikuri/qiskit-tutorials |
In this section, we first judge the version of Python and import the packages of qiskit, math to implement the following code. We show our algorithm on the ibm_qasm_simulator, if you need to run it on the real quantum conputer, please remove the "" in frint of "import Qconfig". | theta_list = [0.01, 0.02, 0.03, 0.04, 0.05, 1.31, 1.32, 1.33, 1.34, 1.35] | _____no_output_____ | Apache-2.0 | community/awards/teach_me_qiskit_2018/quantum_machine_learning/1_K_Means/Quantum K-Means Algorithm.ipynb | Chibikuri/qiskit-tutorials |
Here we define the number pi in the math lib, because we need to use u3 gate. And we also define a list about the parameter theta which we need to use in the u3 gate. As the same above, if you want to implement on the real quantum comnputer, please remove the symbol "" and configure your local Qconfig.py file. | # create Quantum Register called "qr" with 5 qubits
qr = QuantumRegister(5, name="qr")
# create Classical Register called "cr" with 5 bits
cr = ClassicalRegister(5, name="cr")
# Creating Quantum Circuit called "qc" involving your Quantum Register "qr"
# and your Classical Register "cr"
qc = QuantumCircuit(qr, cr, ... | COMPLETED
theta_1:0.01
theta_2:0.02
| Apache-2.0 | community/awards/teach_me_qiskit_2018/quantum_machine_learning/1_K_Means/Quantum K-Means Algorithm.ipynb | Chibikuri/qiskit-tutorials |
Seminar for Lecture 13 "VAE Vocoder"In the lectures, we studied various approaches to creating vocoders. The problem of sound generation is solved by deep generative models. We've discussed autoregressive models that can be reduced to **MAF**. We've considered the reverse analogue of MAF – **IAF**. We've seen how **no... | # ! pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
# ! pip install numpy==1.17.5 matplotlib==3.3.3 tqdm==4.54.0
import torch
from torch import nn
from torch.nn import functional as F
from typing import Union
from math import log, pi, sqrt... | _____no_output_____ | MIT | week_13/seminar.ipynb | ishalyminov/shad_speech |
Introduce auxiliary modules:1. causal convolution – simple convolution with `kernel_size` and `dilation` hyper-parameters, but working in causal way (does not look in the future)2. residual block – main building component of WaveNet architectureYes, WaveNet is everywhere. We can build MAF and IAF with any architecture,... | class CausalConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, dilation=1):
super(CausalConv, self).__init__()
self.padding = dilation * (kernel_size - 1)
self.conv = nn.Conv1d(
in_channels,
out_channels,
kernel_size,
... | _____no_output_____ | MIT | week_13/seminar.ipynb | ishalyminov/shad_speech |
For WaveNet it doesn't matter what it is used for: MAF or IAF - it all depends on our interpretation of the input and output variables.Below is the WaveNet architecture that you are already familiar with from the last seminar. But this time, you will need to implement not inference but forward pass - and it's very simp... | class WaveNet(nn.Module):
def __init__(self, params):
super(WaveNet, self). __init__()
self.front_conv = nn.Sequential(
CausalConv(1, params.residual_channels, params.front_kernel_size),
nn.ReLU())
self.res_blocks = nn.ModuleList()
for b in range(params.num_... | _____no_output_____ | MIT | week_13/seminar.ipynb | ishalyminov/shad_speech |
Excellent 👍! Now we are ready to get started on more complex and interesting things.Do you remember our talks about vocoders built on IAF (Parallel WaveNet or ClariNet Vocoder)? We casually said that IAF we use not just one WaveNet (predicting mu and sigma), but a stack of WaveNets. Actually, let's implement this stac... | class WaveNetFlows(nn.Module):
def __init__(self, params):
super(WaveNetFlows, self).__init__()
self.device = params.device
self.iafs = nn.ModuleList()
for i in range(params.num_flows):
self.iafs.append(WaveNet(params))
def forward(self, z, c):
# z: random s... | _____no_output_____ | MIT | week_13/seminar.ipynb | ishalyminov/shad_speech |
If you are not familiar with VAE framework, please try to figure it out. For example, please familiarize with this [blog post](https://wiseodd.github.io/techblog/2016/12/10/variational-autoencoder/).In short, VAE – is just "modification" of AutoEncoder, which consists of encoder and decoder. VAE allows you to sample fr... | class WaveNetVAE(nn.Module):
def __init__(self, encoder_params, decoder_params):
super(WaveNetVAE, self).__init__()
assert encoder_params.device == decoder_params.device
self.device = encoder_params.device
self.mse_loss = torch.nn.MSELoss()
self.encoder = WaveNet(encoder_par... | _____no_output_____ | MIT | week_13/seminar.ipynb | ishalyminov/shad_speech |
If it sounds plausible **5 points** 🥉 are already yours 🎉! And here the most interesting and difficult part comes: loss function implementation. The `forward` method will return the loss. But lets talk more precisly about our architecture and how it was trained.The encoder of our model $q_{\phi}(z|x)$ is parametreriz... | net = WaveNetVAE(ParamsMAF(), ParamsIAF()).to(device).train()
x = x[:64 * 256]
c = c[:, :64]
net.zero_grad()
loss = net.forward(x.unsqueeze(0).unsqueeze(0), c.unsqueeze(0))
loss.backward()
print(f"Initial loss: {loss.item():.2f}")
ckpt = torch.load(ckpt_path, map_location='cpu')
net.load_state_dict(ckpt['state_dict'... | Initial loss: 6629.40
Optimized loss: 6.45
| MIT | week_13/seminar.ipynb | ishalyminov/shad_speech |
Trigger ExamplesTriggers allow the user to specify a set of actions that are triggered by the result of a boolean expression.They provide flexibility to adapt what analysis and visualization actions are taken in situ. Triggers leverage Ascent's Query and Expression infrastructure. See Ascent's [Triggers](https://ascen... | # cleanup any old results
!./cleanup.sh
# ascent + conduit imports
import conduit
import conduit.blueprint
import ascent
import numpy as np
# helpers we use to create tutorial data
from ascent_tutorial_jupyter_utils import img_display_width
from ascent_tutorial_jupyter_utils import tutorial_gyre_example
import matp... | _____no_output_____ | BSD-3-Clause | src/examples/tutorial/ascent_intro/notebooks/08_ascent_trigger_examples.ipynb | goodbadwolf/ascent |
Trigger Example 1 Using triggers to render when conditions occur | # Use triggers to render when conditions occur
a = ascent.Ascent()
a.open()
# setup actions
actions = conduit.Node()
# declare a question to ask
add_queries = actions.append()
add_queries["action"] = "add_queries"
# add our entropy query (q1)
queries = add_queries["queries"]
queries["q1/params/expression"] = "entr... | _____no_output_____ | BSD-3-Clause | src/examples/tutorial/ascent_intro/notebooks/08_ascent_trigger_examples.ipynb | goodbadwolf/ascent |
These notebooks can be found at https://github.com/jaspajjr/pydata-visualisation if you want to follow along https://matplotlib.org/users/intro.htmlMatplotlib is a library for making 2D plots of arrays in Python.* Has it's origins in emulating MATLAB, it can also be used in a Pythonic, object oriented way. * Easy stu... | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
Everything in matplotlib is organized in a hierarchy. At the top of the hierarchy is the matplotlib “state-machine environment” which is provided by the matplotlib.pyplot module. At this level, simple functions are used to add plot elements (lines, images, text, etc.) to the current axes in the current figure.Pyplot’s ... | plt.plot([0, 1, 2, 3, 4, 5], [0, 2, 4, 6, 8, 10])
x = [0, 1, 2, 3, 4, 5]
y = [0, 2, 4, 6, 8, 10]
plt.plot(x, y) | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
What if we don't want a line? | plt.plot([0, 1, 2, 3, 4, 5],
[0, 2, 5, 7, 8, 10],
marker='o',
linestyle='')
plt.xlabel('The X Axis')
plt.ylabel('The Y Axis')
plt.show(); | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
Simple example from matplotlibhttps://matplotlib.org/tutorials/intermediate/tight_layout_guide.htmlsphx-glr-tutorials-intermediate-tight-layout-guide-py | def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.locator_params(nbins=5)
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
fig, ((ax1, ax2), (ax3, ax4)) = plt.... | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
Date Plotting | import pandas_datareader as pdr
df = pdr.get_data_fred('GS10')
df = df.reset_index()
print(df.info())
df.head()
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
ax.plot_date(df['DATE'], df['GS10']) | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
Bar Plot | fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
x_data = [0, 1, 2, 3, 4]
values = [20, 35, 30, 35, 27]
ax.bar(x_data, values)
ax.set_xticks(x_data)
ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
; | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
Matplotlib basicshttp://pbpython.com/effective-matplotlib.html Behind the scenes* matplotlib.backend_bases.FigureCanvas is the area onto which the figure is drawn * matplotlib.backend_bases.Renderer is the object which knows how to draw on the FigureCanvas * matplotlib.artist.Artist is the object that knows how to ... | fig, (ax1, ax2) = plt.subplots(
nrows=1,
ncols=2,
sharey=True,
figsize=(12, 8))
fig.suptitle("Main Title", fontsize=14, fontweight='bold');
x_data = [0, 1, 2, 3, 4]
values = [20, 35, 30, 35, 27]
ax1.barh(x_data, values);
ax1.set_xlim([0, 55])
#ax1.set(xlabel='Unit of measurement', ylabel='Groups')
ax... | _____no_output_____ | MIT | basic-matplotlib-plotting.ipynb | jaspajjr/pydata-visualisation |
**[Machine Learning Course Home Page](https://www.kaggle.com/learn/machine-learning)**--- This exercise will test your ability to read a data file and understand statistics about the data.In later exercises, you will apply techniques to filter the data, build a machine learning model, and iteratively improve your model... | # Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.machine_learning.ex2 import *
print("Setup Complete") | _____no_output_____ | MIT | exercises/exercise-explore-your-data.ipynb | bobrokerson/kaggle |
Step 1: Loading DataRead the Iowa data file into a Pandas DataFrame called `home_data`. | import pandas as pd
# Path of the file to read
iowa_file_path ='../input/home-data-for-ml-course/train.csv'
# Fill in the line below to read the file into a variable home_data
home_data = pd.read_csv(iowa_file_path)
# Call line below with no argument to check that you've loaded the data correctly
step_1.check() | _____no_output_____ | MIT | exercises/exercise-explore-your-data.ipynb | bobrokerson/kaggle |
Step 2: Review The DataUse the command you learned to view summary statistics of the data. Then fill in variables to answer the following questions | # Print summary statistics in next line
#print(home_data.info())
home_data[['YearBuilt','YrSold']].describe()
# What is the average lot size (rounded to nearest integer)?
avg_lot_size_1 = home_data.LotArea.mean()
avg_lot_size = round(avg_lot_size_1)
print(avg_lot_size)
# As of today, how old is the newest home (current... | _____no_output_____ | MIT | exercises/exercise-explore-your-data.ipynb | bobrokerson/kaggle |
Procedures and Functions TutorialMLDB is the Machine Learning Database, and all machine learning operations are done via Procedures and Functions. Training a model happens via Procedures, and applying a model happens via Functions. The notebook cells below use `pymldb`'s `Connection` class to make [REST API](../../../... | from pymldb import Connection
mldb = Connection("http://localhost") | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
Loading a Dataset The classic [Iris Flower Dataset](http://en.wikipedia.org/wiki/Iris_flower_data_set) isn't very big but it's well-known and easy to reason about so it's a good example dataset to use for machine learning examples.We can import it directly from a remote URL: | mldb.put('/v1/procedures/import_iris', {
"type": "import.text",
"params": {
"dataFileUrl": "file://mldb/mldb_test_data/iris.data",
"headers": [ "sepal length", "sepal width", "petal length", "petal width", "class" ],
"outputDataset": "iris",
"runOnCreation": True
}
}) | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
A quick look at the dataWe can use the [Query API](../../../../doc/builtin/sql/QueryAPI.md.html) to get the data into a Pandas DataFrame to take a quick look at it. | df = mldb.query("select * from iris")
df.head()
%matplotlib inline
import seaborn as sns, pandas as pd
sns.pairplot(df, hue="class", size=2.5) | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
Unsupervised Machine Learning with a `kmeans.train` ProcedureWe will create and run a [Procedure](../../../../doc/builtin/procedures/Procedures.md.html) of type [`kmeans.train`](../../../../doc/builtin/procedures/KmeansProcedure.md.html). This will train an unsupervised K-Means model and use it to assign each row in t... | mldb.put('/v1/procedures/iris_train_kmeans', {
'type' : 'kmeans.train',
'params' : {
'trainingData' : 'select * EXCLUDING(class) from iris',
'outputDataset' : 'iris_clusters',
'numClusters' : 3,
'metric': 'euclidean',
"runOnCreation": True
}
}) | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
Now we can look at the output dataset and compare the clusters the model learned with the three types of flower in the dataset. | mldb.query("""
select pivot(class, num) as *
from (
select cluster, class, count(*) as num
from merge(iris_clusters, iris)
group by cluster, class
)
group by cluster
""") | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
As you can see, the K-means algorithm doesn't do a great job of clustering this data (as is mentioned in the Wikipedia article!). Supervised Machine Learning with `classifier.train` and `.test` ProceduresWe will now create and run a [Procedure](../../../../doc/builtin/procedures/Procedures.md.html) of type [`classifie... | mldb.put('/v1/procedures/iris_train_classifier', {
'type' : 'classifier.train',
'params' : {
'trainingData' : """
select
{* EXCLUDING(class)} as features,
class as label
from iris
where rowHash() % 5 = 0
""",
"algori... | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
We can now test the classifier we just trained on the subset of the data we didn't use for training. To do so we use a procedure of type [`classifier.test`](../../../../doc/builtin/procedures/Accuracy.md.html). | rez = mldb.put('/v1/procedures/iris_test_classifier', {
'type' : 'classifier.test',
'params' : {
'testingData' : """
select
iris_classify({
features: {* EXCLUDING(class)}
}) as score,
class as label
from iris
... | <Response [201]>
| Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
The procedure returns a confusion matrix, which you can compare with the one that resulted from the K-means procedure. | pd.DataFrame(runResults["confusionMatrix"])\
.pivot_table(index="actual", columns="predicted", fill_value=0) | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
As you can see, the decision tree does a much better job of classifying the data than the K-means model, using 20% of the examples as training data.The procedure also returns standard classification statistics on how the classifier performed on the test set. Below are performance statistics for each label: | pd.DataFrame.from_dict(runResults["labelStatistics"]).transpose() | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
They are also available, averaged over all labels: | pd.DataFrame.from_dict({"weightedStatistics": runResults["weightedStatistics"]}) | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
Scoring new examplesWe can call the Function REST API endpoint to classify a never-before-seen set of measurements like this: | mldb.get('/v1/functions/iris_classify/application', input={
"features":{
"petal length": 1,
"petal width": 2,
"sepal length": 3,
"sepal width": 4
}
}) | _____no_output_____ | Apache-2.0 | container_files/tutorials/Procedures and Functions Tutorial.ipynb | mldbai/mldb |
Assignment 2 - Elementary Probability and Information Theory Boise State University NLP - Dr. Kennington Instructions and Hints:* This notebook loads some data into a `pandas` dataframe, then does a small amount of preprocessing. Make sure your data can load by stepping through all of the cells up until question 1. *... | import pandas as pd
data = pd.read_csv('pnp-train.txt',delimiter='\t',encoding='latin-1', # utf8 encoding didn't work for this
names=['type','name']) # supply the column names for the dataframe
# this next line creates a new column with the lower-cased first word
data['first_word'] = data['name'].m... | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
1. Write a probability function/distribution $P(T)$ over the types. Hints:* The Counter library might be useful: `from collections import Counter`* Write a function `def P(T='')` that returns the probability of the specific value for T* You can access the types from the dataframe by calling `data['type']` | from collections import Counter
def P(T=''):
global counts
global data
counts = Counter(data['type'])
return counts[T] / len(data['type'])
counts | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
2. What is `P(T='movie')` ? | P(T='movie') | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
3. Show that your probability distribution sums to one. | import numpy as np
round(np.sum([P(T=x) for x in set(data['type'])]), 4) | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
4. Write a joint distribution using the type and the first word of the nameHints:* The function is $P2(T,W_1)$* You will need to count up types AND the first words, for example: ('person','bill)* Using the [itertools.product](https://docs.python.org/2/library/itertools.htmlitertools.product) function was useful for me... | def P2(T='', W1=''):
global count
count = data[['type', 'first_word']]
return len(count.loc[(count['type'] == T) & (count['first_word'] == W1)]) / len(count) | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
5. What is P2(T='person', W1='bill')? What about P2(T='movie',W1='the')? | P2(T='person', W1='bill')
P2(T='movie', W1='the') | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
6. Show that your probability distribution P(T,W1) sums to one. | types = Counter(data['type'])
words = Counter(data['first_word'])
retVal = 0
for x in types:
for y in words:
retVal = retVal + P2(T=x,W1=y)
print(round(retVal,4)) | 1.0
| AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
7. Make a new function Q(T) from marginalizing over P(T,W1) and make sure that Q(T) sums to one.Hints:* Your Q function will call P(T,W1)* Your check for the sum to one should be the same answer as Question 3, only it calls Q instead of P. | def Q(T=''):
words = Counter(data['first_word'])
retVal = 0
for x in words:
retVal = retVal + P2(T,W1=x)
return retVal
Q('movie')
round(np.sum([Q(T=x) for x in set(data['type'])]), 4) | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
8. What is the KL Divergence of your Q function and your P function for Question 1?* Even if you know the answer, you still need to write code that computes it. I wasn't quite sure how to properly do this question so it's kind of just half implemented. Although I do know that it should be 0.0 | import math
(P('drug') * math.log(P('drug') / Q('drug')) + P('movie') * math.log(P('movie') / Q('movie'))) | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
9. Convert from P(T,W1) to P(W1|T) Hints:* Just write a comment cell, no code this time. * Note that $P(T,W1) = P(W1,T)$ Given that P(T,W1) = P(W1,T) then we can infer that P(W1|T) = (P(W1,T)/P(T)) (try to use markdown math formating, answer in this cell) 10. Write a function `Pwt` (that calls the functions you alrea... | def Pwt(W1='',T=''):
return P2(T=T,W1=W1)/P(T=T) | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
11. What is P(W1='the'|T='movie')? | Pwt(W1='the',T='movie') | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.