bookloveru2
2021年6月27日8 分
最終更新: 2021年11月1日
※バーガーメニューとサイドメニューのみデータ化しており、ドリンクとマックカフェバイバリスタは含んでおりません。
# @title Colab から Google Drive を使う(Google Drive のスペースをマウント)
from google.colab import drive
drive.mount('/content/drive')
import numpy as np # 数値計算
import pandas as pd # データフレーム操作
from sklearn import linear_model # 機械学習の線形モデル
from sklearn.preprocessing import StandardScaler # 標準化
# データセットの読み込み 日本語が入っているcsvファイルは、UTF-8では読めないからShift_JIS に変更(encoding=)
df = pd.read_csv('/content/drive/My Drive//mac.csv', encoding="shift-jis")
df
# カロリーでソートし、デブまっしぐらのメニュー上位5位を表示
debu = df.sort_values(by = "エネルギーkcal",ascending=False)
debu.head(5)
# 値段でソートし、お財布に厳しいメニュー上位5位を表示
price = df.sort_values(by = "値段",ascending=False)
price.head(5)
# えびちゃんを探せ!
df.query('商品名.str.contains("えび")', engine='python')
# 各列の要約統計量を取得
df.describe()
df1 = df.drop(['商品名'], axis=1)
# 標準化
scaler = StandardScaler()
scaler.fit(np.array(df1))
df_std = scaler.transform(np.array(df1))
df_std = pd.DataFrame(df_std,columns=df1.columns)
# 目的変数(Y)
Y1 = np.array(df_std['値段'])
# 説明変数(X)
# 説明変数のみ抽出して変数Xに格納
X1 = df_std.loc[:, '製品重量g/個':'食塩相当量g']
print("標準化後の説明変数X1-----------\n{}".format(X1))
print("標準化後の目的変数Y1-----------\n{}".format(Y1))
# 線形モデルのインスタンスを生成
model = linear_model.LinearRegression()
# データを渡してモデルを生成
model.fit(X1,Y1)
# 係数の値を取得し、変数coefficientに格納
coefficient = model.coef_
# カラム名とインデックス名を付与してデータフレームに変換
df_coefficient = pd.DataFrame(coefficient, columns=["標準化偏回帰係数"], index=[X1.columns])
print(df_coefficient)
# statsamodelでP値 t値をチェック
import statsmodels.api as sm
x_add_const = sm.add_constant(X1)
model_S = sm.OLS(Y1, x_add_const).fit()
print(model_S.summary())
※ナイアシンは水に溶ける水溶性ビタミンのひとつで、ビタミンB群の仲間です。ナイアシンはニコチン酸とニコチンアミドの総称ですが、体内でトリプトファンという必須アミノ酸からも合成することができ、私たちはこれらをナイアシンとして利用しています。=ビタミン
# p値が0.1以上の説明変数を除外
Z = df_std[['製品重量g/個', "ナイアシンmg", "ビタミンCmg"]]
Y1 = Y1 # 目的変数
# データを渡してモデルを生成
model.fit(Z,Y1)
# 係数の値を取得し、変数coefficientに格納
coefficient = model.coef_
# カラム名とインデックス名を付与してデータフレームに変換
df_coefficient = pd.DataFrame(coefficient, columns=["標準化偏回帰係数"], index=[Z.columns])
print(df_coefficient)
x_add_constant1 = sm.add_constant(Z)
result = sm.OLS(Y1, x_add_constant1).fit()
print(result.summary())
# 製品重量g/個上位10位を表示
a = df.sort_values(by = "製品重量g/個",ascending=False)
a.head(10)
# ナイアシンmg/個上位10位を表示
c = df.sort_values(by = "ナイアシンmg")
c.head(10).append(c.tail())
# ビタミンCmg/個上位10位を表示
b = df.sort_values(by = "ビタミンCmg",ascending=False)
b.head(10)
# @title Colab から Google Drive を使う(Google Drive のスペースをマウント)
from google.colab import drive
drive.mount('/content/drive')
import numpy as np # 数値計算
import pandas as pd # データフレーム操作
from sklearn import linear_model # 機械学習の線形モデル
from sklearn.preprocessing import StandardScaler # 標準化
# データセットの読み込み 日本語が入っているcsvファイルは、UTF-8では読めないからShift_JIS に変更(encoding=)
df = pd.read_csv('/content/drive/My Drive//mac.csv', encoding="shift-jis")
df
# カロリーでソートし、デブまっしぐらのメニュー上位5位を表示
debu = df.sort_values(by = "エネルギーkcal",ascending=False)
debu.head(5)
# 値段でソートし、お財布に厳しいメニュー上位5位を表示
price = df.sort_values(by = "値段",ascending=False)
price.head(5)
# えびちゃんを探せ!
df.query('商品名.str.contains("えび")', engine='python')
# 各列の要約統計量を取得
df.describe()
df1 = df.drop(['商品名'], axis=1)
# 標準化
scaler = StandardScaler()
scaler.fit(np.array(df1))
df_std = scaler.transform(np.array(df1))
df_std = pd.DataFrame(df_std,columns=df1.columns)
# 目的変数(Y)
Y1 = np.array(df_std['値段'])
# 説明変数(X)
# 説明変数のみ抽出して変数Xに格納
X1 = df_std.loc[:, '製品重量g/個':'食塩相当量g']
print("標準化後の説明変数X1-----------\n{}".format(X1))
print("標準化後の目的変数Y1-----------\n{}".format(Y1))
# 線形モデルのインスタンスを生成
model = linear_model.LinearRegression()
# データを渡してモデルを生成
model.fit(X1,Y1)
# 係数の値を取得し、変数coefficientに格納
coefficient = model.coef_
# カラム名とインデックス名を付与してデータフレームに変換
df_coefficient = pd.DataFrame(coefficient, columns=["標準化偏回帰係数"], index=[X1.columns])
print(df_coefficient)
# statsamodelでP値 t値をチェック
import statsmodels.api as sm
x_add_const = sm.add_constant(X1)
model_S = sm.OLS(Y1, x_add_const).fit()
print(model_S.summary())
# p値が0.1以上の説明変数を除外
Z = df_std[['製品重量g/個', "ナイアシンmg", "ビタミンCmg"]]
Y1 = Y1 # 目的変数
# データを渡してモデルを生成
model.fit(Z,Y1)
# 係数の値を取得し、変数coefficientに格納
coefficient = model.coef_
# カラム名とインデックス名を付与してデータフレームに変換
df_coefficient = pd.DataFrame(coefficient, columns=["標準化偏回帰係数"], index=[Z.columns])
print(df_coefficient)
x_add_constant1 = sm.add_constant(Z)
result = sm.OLS(Y1, x_add_constant1).fit()
print(result.summary())
# 切片を取得
print("切片: {}".format(model.intercept_))
# 決定係数を取得
print("決定係数: {}".format(model.score(Z, Y1)))
# 製品重量g/個上位10位を表示
a = df.sort_values(by = "製品重量g/個",ascending=False)
a.head(10)
# ナイアシンmg/個上位10位を表示
c = df.sort_values(by = "ナイアシンmg")
c.head(10).append(c.tail())
# ビタミンCmg/個上位10位を表示
b = df.sort_values(by = "ビタミンCmg",ascending=False)
b.head(10)
y = df[['値段']]
x1 = df[['製品重量g/個']]
x2 = df[['ビタミンCmg']]
from mpl_toolkits.mplot3d import Axes3D #3Dplot
import matplotlib.pyplot as plt
import seaborn as sns
fig=plt.figure()
ax=Axes3D(fig)
ax.scatter3D(x1, x2, y, label='Dataset')
ax.set_xlabel("x1")
ax.set_ylabel("x2")
ax.set_zlabel("y")
plt.show()
pythonでプログラミングがしたい!!
pythonを学びたい!という方には、
オンラインプログラミング教室『Aidemy アイデミー』がお勧めです。
ご自身でプログラム環境を用意する必要は無く、サイトへアクセスするだけです。 創業者は東京大学工学部卒の石川聡彦さん。
著書に『人工知能プログラミングのための数学がわかる本』(KADOKAWA/2018年)など。
無料で、お試しもできますので安心です。
お時間ある方は下記リンクを覗いてみてはいかがでしょうか(*'ω'*)。