统计算法_数值/线性关系度量

继续统计算法,这次也没什么特别的,还没到那么深入,也是比较基础的
1、方差-样本
2、协方差(标准差)-样本
3、变异系数
4、相关系数


依然是先造个list,这次把这个功能写个函数,方便以后调用,另外上一篇写过的函数这次也会继承
def create_rand_list(min_num,max_num,count_list):
  case_list = []
  while len(case_list) < count_list:
    rand_float = random.uniform(min_num,max_num)
    if rand_float in case_list:
      continue
    case_list.append(rand_float)
  case_list = [round(case,2) for case in case_list]
  return case_list


下面是历史函数
sum_fun() #累加
len_fun() #统计个数
multiply_fun() #累乘
sum_mean_fun() #算数平均数
sum_mean_rate() #算数平均数计算回报
median_fun() #中位数
modes_fun() #众数
ext_minus_fun() #极差
geom_mean_fun() #几何平均数
geom_mean_rate() #几何平均回报

新函数代码

import random

# 先生成一个随机list,已有函数,不赘述
rand_list = [15.79, 6.83, 12.83, 22.32, 17.92, 6.29, 10.19, 10.13, 24.23, 25.56]

# 1、方差-样本S^2,list中的每个元素减整个list的平均数的平方累加,结果比个数-1,方差总量不-1
def var_fun(rand_list):
  mean_num = sum_mean_fun(rand_list) #计算平均数
  len_num = len_fun(rand_list) #计算总量
  var_list = [(x-mean_num)**2 for x in rand_list]
  var_sum = sum_fun(var_list)
  var_num = var_sum/(len_num - 1)
  return var_num
# 2、协方差(标准差)-样本S,这个简单,用方差开平方就可以了 def covar_fun(rand_list):   var_num = var_fun(rand_list)
  covar_num = var_num ** 0.5
  return covar_num
# 3、变异系数CV,变异程度度量,协方差/算数平均数*100% # 说明(百度百科):在进行数据统计分析时,如果变异系数大于15%,则要考虑该数据可能不正常,应该剔除 def trans_coef_fun(rand_list):   covar_num = covar_fun(rand_list)
  mean_num = sum_mean_fun(rand_list)
  trans_coef_num = covar_num / mean_num
  return trans_coef_num
# 4、相关系数-样本r,表示两个维之间的线性关系,-1 < r < 1,越接近1关系维间的关系越强 # 因为是两个维,因此需要输入两维的list,算法比较麻烦 ''' ((x1-mean(x))(y1-mean(y))+(x2-mean(x))(y2-mean(y))+...(xn-mean(x))(yn-mean(y))) /((x1-mean(x))^2+(x2-mean(x))^2+...(xn-mean(x))^2)^0.5*((y1-mean(y))^2+(y2-mean(y))^2+...(yn-mean(y))^2)^0.5 ''' x_list = rand_list y_list = [4.39, 13.84, 9.21, 9.91, 15.69, 14.92, 25.77, 23.99, 8.15, 25.07] def pearson_fun(x_list,y_list):   x_mean = sum_mean_fun(x_list)
  y_mean = sum_mean_fun(y_list)
  len_num = len_fun(x_list)
  if len_num == len_fun(y_list):
    xy_multiply_list = [(x_list[i]-x_mean)*(y_list[i]-y_mean) for i in range(len_num)]
    xy_multiply_num = sum_fun(xy_multiply_list)
  else:
    print 'input list wrong,another input try'
    return None
  x_covar_son_list = [(x-x_mean)**2 for x in x_list]
  y_covar_son_list = [(y-y_mean)**2 for y in y_list]
  x_covar_son_num = sum_fun(x_covar_son_list)
  y_covar_son_num = sum_fun(y_covar_son_list)
  xy_covar_son_multiply_num = (x_covar_son_num ** 0.5) * (y_covar_son_num ** 0.5)
  pearson_num = xy_multiply_num / xy_covar_son_multiply_num
  return pearson_num

 

posted @ 2018-08-05 01:18 咻_python 阅读(...) 评论(...) 编辑 收藏