第一个线性回归程序(基于Jupyter)
import pandas as pd
import seaborn as sns
sns.set(context="notebook", style="whitegrid", palette="dark")
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
df = pd.read_csv('ex1data1.txt', names=['population', 'profit'])#读取数据并赋予列名
df.head()#看前五行
df.info()
sns.lmplot('population', 'profit', df, size=6, fit_reg=False)
plt.show()
def get_X(df):#读取特征
ones = pd.DataFrame({'ones': np.ones(len(df))})#ones是m行1列的dataframe
data = pd.concat([ones, df], axis=1) # 合并数据,根据列合并
return data.iloc[:, :-1].as_matrix() # 这个操作返回 ndarray,不是矩阵
def get_y(df):#读取标签
return np.array(df.iloc[:, -1])
def normalize_feature(df):
return df.apply(lambda column: (column - column.mean()) / column.std())#特征缩放
def linear_regression(X_data, y_data, alpha, epoch, optimizer=tf.train.GradientDescentOptimizer):# 这个函数是旧金山的一个大神Lucas Shen写的
# placeholder for graph input
X = tf.placeholder(tf.float32, shape=X_data.shape)
y = tf.placeholder(tf.float32, shape=y_data.shape)
# construct the graph
with tf.variable_scope('linear-regression'):
W = tf.get_variable("weights",
(X_data.shape[1], 1),
initializer=tf.constant_initializer()) # n*1
y_pred = tf.matmul(X, W) # m*n @ n*1 -> m*1
loss = 1 / (2 * len(X_data)) * tf.matmul((y_pred - y), (y_pred - y), transpose_a=True) # (m*1).T @ m*1 = 1*1
opt = optimizer(learning_rate=alpha)
opt_operation = opt.minimize(loss)
# run the session
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
loss_data = []
for i in range(epoch):
_, loss_val, W_val = sess.run([opt_operation, loss, W], feed_dict={X: X_data, y: y_data})
loss_data.append(loss_val[0, 0]) # because every loss_val is 1*1 ndarray
if len(loss_data) > 1 and np.abs(loss_data[-1] - loss_data[-2]) < 10 ** -9: # early break when it's converged
# print('Converged at epoch {}'.format(i))
break
# clear the graph
tf.reset_default_graph()
return {'loss': loss_data, 'parameters': W_val} # just want to return in row vector format
data = pd.read_csv('ex1data1.txt', names=['population', 'profit'])#读取数据,并赋予列名
data.head()#看下数据前5行
X = get_X(data)
print(X.shape, type(X))
y = get_y(data)
print(y.shape, type(y))
#看下数据维度
theta = np.zeros(X.shape[1])#X.shape[1]=2,代表特征数n
def lr_cost(theta, X, y):
# """
# X: R(m*n), m 样本数, n 特征数
# y: R(m)
# theta : R(n), 线性回归的参数
# """
m = X.shape[0]#m为样本数
inner = X @ theta - y # R(m*1),X @ theta等价于X.dot(theta)
# 1*m @ m*1 = 1*1 in matrix multiplication
# but you know numpy didn't do transpose in 1d array, so here is just a
# vector inner product to itselves
square_sum = inner.T @ inner
cost = square_sum / (2 * m)
return cost
lr_cost(theta, X, y)#返回theta的值
def gradient(theta, X, y):
m = X.shape[0]
inner = X.T @ (X @ theta - y) # (m,n).T @ (m, 1) -> (n, 1),X @ theta等价于X.dot(theta)
return inner / m
def batch_gradient_decent(theta, X, y, epoch, alpha=0.01):
# 拟合线性回归,返回参数和代价
# epoch: 批处理的轮数
# """
cost_data = [lr_cost(theta, X, y)]
_theta = theta.copy() # 拷贝一份,不和原来的theta混淆
for _ in range(epoch):
_theta = _theta - alpha * gradient(_theta, X, y)
cost_data.append(lr_cost(_theta, X, y))
return _theta, cost_data
#批量梯度下降函数
epoch = 500
final_theta, cost_data = batch_gradient_decent(theta, X, y, epoch)
final_theta
#最终的theta
cost_data
# 看下代价数据
# 计算最终的代价
lr_cost(final_theta, X, y)
ax = sns.tsplot(cost_data, time=np.arange(epoch+1))
ax.set_xlabel('epoch')
ax.set_ylabel('cost')
plt.show()
#可以看到从第二轮代价数据变换很大,接下来平稳了
b = final_theta[0] # intercept,Y轴上的截距
m = final_theta[1] # slope,斜率
plt.scatter(data.population, data.profit, label="Training data")
plt.plot(data.population, data.population*m + b, label="Prediction")
plt.legend(loc=2)
plt.show()
第一个线性回归程序(基于Jupyter)的更多相关文章
- TODO:即将开发的第一个小程序
TODO:即将开发的第一个小程序 微信小程序是一种全新的连接用户与服务的方式,它可以在微信内被便捷地获取和传播,同时具有出色的使用体验.个人理解小程序是寄宿在微信平台上的一个前端框架,具有跨平台功能, ...
- ASP.NET MVC 5 03 - 安装MVC5并创建第一个应用程序
不知不觉 又逢年底, 穷的钞票 所剩无几. 朋友圈里 各种装逼, 抹抹眼泪 MVC 继续走起.. 本系列纯属学习笔记,如果哪里有错误或遗漏的地方,希望大家高调指出,当然,我肯定不会低调改正的.(开个小 ...
- SharePoint使用BCS开发你第一个应用程序(三)
SharePoint使用BCS开发你第一个应用程序(三) 创建外部内容类型. 创建外部内容类型有三种不同方式: 1. 在记事本上手写XML代码(不推荐). 2. 使用SharePoin ...
- 小程序基于疼讯qcloud的nodejs开发服务器部署
腾讯,疼讯,很疼. 请慎重看腾讯给出的文档,最好做一个笔记. 我只能说我能力有限,在腾讯云小程序的文档中跳了n天. 最后还是觉得记录下来,以防止我的cpu过载给烧了. 此文档是对<小程序 ...
- 微信小程序-基于高德地图API实现天气组件(动态效果)
微信小程序-基于高德地图API实现天气组件(动态效果) 在社区翻腾了许久,没有找到合适的天气插件.迫不得已,只好借鉴互联网上的web项目,手动迁移到小程序中使用.现在分享到互联网社区中,帮助后续有 ...
- 如何基于Jupyter notebook搭建Spark集群开发环境
摘要:本文介绍如何基于Jupyter notebook搭建Spark集群开发环境. 本文分享自华为云社区<基于Jupyter Notebook 搭建Spark集群开发环境>,作者:apr鹏 ...
- Unity Shaders 第一个默认程序分析
Unity Shaders 第一个默认程序 Shader "Custom/Shader" { Properties { _MainTex ("Base (RGB)&quo ...
- Maven的第一个小程序
这里是介绍关于maven的第一个小程序 关于maven的安装 : Install Maven in your computer 先看看目录结构: 这是本来的项目目录结构,由于maven有自己的目录结构 ...
- Xamarin iOS编写第一个应用程序创建工程
Xamarin iOS编写第一个应用程序创建工程 在Xcode以及Xamarin安装好后,就可以在Xamarin Studio中编写程序了.本节将主要讲解在Xamarin Studio中如何进行工程的 ...
随机推荐
- CSS 高级选择器
相信各位如我一样的“抠图崽”和前端大佬们,在写网页样式的实话,总是免不了写下各种各样的选择器,再给选择的元素写入样式.最基本的元素选择器.class选择器.ID选择器等就不再过多的说了,相信大家都熟的 ...
- Elasticsearch 映射操作
一.创建 语法: PUT /索引库名称/_mapping/类型名称 { "properties": { "字段名": { "type": 类 ...
- MongoDB如何释放空闲空间?
当我们从MongoDB中删除文档或集合时,MongoDB并不会将已经占用了的磁盘空间释放,它会一直维护已经占用了磁盘空间的数据文件,尽管数据文件中可能存在大大小小的空记录列表(empty record ...
- day 24 内置模块re
1.正则表达式,匹配字符串 正则表达式是对字符串操作的一种逻辑公式.我们一般使用正则表达式对字符串镜子那个匹配和过滤,使用正则的优缺点: 优点: 灵活,功能性强,逻辑性强 缺点: 上手难.一旦上手,会 ...
- flask的查询,一对多,多对多
模型的关联: 一对多 class Role(db.Model): us = db.relationship('User',backref='role',lazy='dynamic') class Us ...
- verilog中参数传递与参数定义中#的作用(二)
一.module内部有效的定义 用parameter来定义一个标志符代表一个常量,称作符号常量,他可以提高程序的可读性和可维护性.parameter是参数型数据的关键字,在每一个赋值语句的右边都必须是 ...
- Java技术——Iterator和Enumeration的不同
个函数接口.Iterator除了能读取集合的数据之外,也能对数据进行删除操作.尽管前者还没有被弃用但是已经被后者所代替了,Enumeration已经过时的,之所以没有被弃用是因为它仍被几种从以前版本遗 ...
- Windows下MySQL多实例运行(转)
关键字:Windows下MySQL多实例运行 阅读前注意事项: 1.有的版本的data目录不直接放在mysql安装目录下,有可能在:C:\ProgramData\MySQL\MySQL Server ...
- 北京Uber优步司机奖励政策(12月13日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
- 成都Uber优步司机奖励政策(1月16日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...