深度学习之iris分类

5 篇文章 0 订阅
5 篇文章 0 订阅
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import *
from keras.wrappers.scikit_learn import *
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score, KFold
from sklearn.preprocessing import LabelEncoder
from keras.models import model_from_json
# 设置参数
seed = 13
np.random.seed(seed)
# 读取数据
df = pd.read_csv("E:/study/tensorflow/project/machinelearning/iris/data/Iris.csv")
x = df.values[:, 1:5].astype(float)
y = df.values[:, 5]
# 将y列的数据字符串转换成数字再转换成onehot
encoder = LabelEncoder()
y_encoder = encoder.fit_transform(y)
y_onehot = np_utils.to_categorical(y_encoder)

#
#
# # 定义神经网络模型
def baseline_model():
    model = Sequential()
    # 添加隐藏层
    model.add(Dense(7, input_dim=4, activation="tanh"))  # 网络层数,输入的列数,激活函数
    model.add(Dense(3, activation="softmax"))
    model.compile(loss="mean_squared_error", optimizer="sgd", metrics=["accuracy"])
    return model


# # 通过交叉熵验证训练模型
estimator = KerasClassifier(build_fn=baseline_model, epochs=20, batch_size=1, verbose=1)
print(estimator)
# # 设置参数evalute
kfold = KFold(n_splits=10, shuffle=True, random_state=seed)
print(kfold)
result = cross_val_score(estimator, x, y_onehot, cv=kfold, verbose=0)
print("Accuray of cross valitaion, means %.2f, std %2f" % (result.mean(), result.std()))

# save model
print("======================")
estimator.fit(x, y_onehot)

model_json = estimator.model.to_json()
with open("model.json", "w") as jsonfile:
    jsonfile.write(model_json)
# 保存参数
estimator.model.save_weights("model.h5")
print("保存模型成功")

# 读取模型
json_file = open("model.json", "r")
loaded_model_json = json_file.read()
json_file.close()

# 读取模型参数权重
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights("model.h5")
print("loaded model successful")
# 进行预测
predicted = loaded_model.predict(x)
print("prediction rob:" + str(predicted))
predicted_label = loaded_model.predict_classes(x)
print("predicted_label:" + str(predicted_label))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值